我的应用中有多项服务,例如AuthenticateService
,UserService
,可以从API请求数据。
在大多数服务功能中都有一些常用标头,例如authentication token
和Content-Type header
。
我想将这些标题保留在单个类中,并在请求数据时在服务中使用它们。
我尝试创建一个custom export class
并通过在其中定义函数来获取这些函数,但它会产生一些错误。
Angular 2/4
从服务中访问的类
import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
@Injectable()
export class MainService {
commonHeaders(){
let headers = new Headers({
'Content-Type': 'application/json',
});
return headers;
}
AuthorizedRequestCommonHeaders() {
let headers = new Headers({
'Content-Type': 'application/json',
});
headers.append('Authorization', 'Basic ' + (localStorage.getItem('auth_token')) );
return headers;
}
}
我尝试访问如下 AuthenticationService.ts
import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'
import { MainService } from './main-service';
@Injectable()
export class AuthenticationService {
login(email: string, password: string) {
let headers = this.MainService.commonHeaders();
let options = new RequestOptions({
headers: headers
});
let postData = {
email: email,
password: password
}
return this.http.post(this.oauthUrl, JSON.stringify(postData) , options)
.map((response: Response) => {
let result = response.json();
if (result && result.token) {
localStorage.setItem('auth_token', JSON.stringify(result.token));
}
});
}
错误消息
属性'commonHeaders'在'MainService'类型上不存在。
答案 0 :(得分:0)
通过导入它可以在任何地方使用的通用功能
import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
@Injectable()
export class MainService {
AuthorizedRequestCommonHeaders() {
let headers = commonHeaders();
headers.append('Authorization', 'Basic ' + (localStorage.getItem('auth_token')) );
return headers;
}
}
export function commonHeaders(){ //keep this is main service or any other but make sure to provide proper path
let headers = new Headers({
'Content-Type': 'application/json',
});
return headers;
}
AuthenticationService.ts
import { commonHeaders } from './main-service';
@Injectable()
export class AuthenticationService {
login(email: string, password: string) {
let headers = commonHeaders();
}