您好我已经创建了一个通用服务,我可以使用通用http请求创建对象。
我现在面临的挑战是,如果用户经过身份验证,我会将每个创建的对象传递给他们的标头(我将获得一个令牌作为响应,存储在localStorage中)
所以基本上我可以在任何级别创建这些自定义http对象(按注入组件)。所有这些都没有设置Authentication Header。用户通过身份验证后,所有这些对象都将设置其身份验证标头。
这是plunker
export class App {
myHttpObject1;
constructor(private myAuth:MyAuth, private myDatabase:MyDatabase) {
this.name = 'Angular2 (Release Candidate!)'
this.myHttpObject1 = this.myDatabase.httpSchema('users')
this.myHttpObject1.log()
// this.myHttpObject1.someOtherMethodes()...
}
login(){
this.myAuth.login()
}
showHeaders(){
this.myHttpObject1.log()
}
}
下面是服务,一个是模拟登录。
@Injectable()
export class MyDatabase{
private base_url:string;
private headers :Headers;
constructor(){
this.base_url = 'https://jsonplaceholder.typicode.com/';
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
this.headers.append('Authorization','');
}
public httpSchema(path:string){
return new MyHttpObject(path, this.headers || new Headers())
}
}
class MyHttpObject{
constructor(public url:string, public headers:Headers){
}
log(){
console.log(this.url)
console.log(this.headers)
}
post(){
console.log('here could be a http post')
}
}
@Injectable()
export class MyAuth{
login(){
setTimeout(()=>{
console.log('logged In');
localStorage.setItem('token':'mytoken');
},2000)
}
}
答案 0 :(得分:0)
查看Http Injector,它拦截调用并将所需内容添加到http对象。