![](/img/trans.png)
[英]Angular2: How to subscribe to Http.post observable inside a service and a component properly?
[英]How to create a new Observable which is subscribed to Observable returned by http.post method in angular2?
我正在创建一个 Angular2 服务。 我使用了返回 EventEmmiter 的 http.post 方法,根据我接下来通过的文档并返回 lambdas。 https://angular.io/docs/js/latest/api/http/Http-class.html
next lambda 按预期工作,但根本没有调用 return lambda。
当我尝试返回 this.user 时。 由于后期操作尚未完成,它为空。 在 auth 响应返回之前,我应该怎么做才能等待。
如果我选择进行反应式编程并希望返回 Rx.Observable 作为此方法的返回。 我如何创建这个 Rx.Observable 它将订阅 http post observable complete 事件。
@Injectable()
export class LoginService {
http:Http;
headers:Headers;
user:User;
constructor(http: Http) {
this.http=http;
this.headers=new Headers();
this.headers.set('Content-Type','application/json');
this.user = new User();
}
authenticateUser(credential:Credential) {
credential.type = 'normal';
this.http.post('http://localhost:8000/api/v1/auth',
JSON.stringify(credential),
{
headers: this.headers
}
).observer({
next: (res) => {
if(res.json()._error_type){
console.log('Error Occured');
}
console.log(res.json());
this.user.authToken = res.json().auth_token;
},
return: () => {
console.log("Logged In");
return "LoggedIn Success"
}}
);
console.log(this.user);
return this.user;
}
}
export class User{
authToken:String;
}
export class Credential{
username:string;
password:string;
type:string;
}
这就是我将可观察字符串附加到 http 调用响应的方式
authenticateUser(credential:Credential):Rx.Observable<string> {
credential.type = 'normal';
return Rx.Observable.create<string>(
observer => {
var val:String;
this.http.post('http://localhost:8000/api/v1/auth',
JSON.stringify(credential),
{
headers: this.headers
}
).toRx().map(res => res.json()).subscribe(
(res) => {
if(res._error_type){
console.log('Error Occured');
observer.onError('ErrorOccured');
} else {
this.user = new User();
this.user.authToken = res.auth_token;
observer.onNext('LoginSuccess');
}
observer.onCompleted();
});
return () => console.log('disposed')
}
);
}
这是调用 LoginService 的 UI 组件
this.loginService.authenticateUser(credential).subscribe(val => {console.log('result:' + val)});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.