![](/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.