我正在创建一个 Angular2 服务。我使用了 http.post 方法,该方法返回 EventEmmiter,并根据我接下来传递的文档并返回 lambda。 https://angular.io/docs/js/latest/api/http/Http-class.html
下一个 lambda 按预期工作,但返回 lambda 根本没有被调用。
当我尝试返回 this.user 时。由于后期操作尚未完成,因此它为空。在身份验证响应返回之前我应该做什么才能等待。
如果我选择进行响应式(Reactive)编程并希望返回 Rx.Observable 作为此方法的返回。我如何创建这个 Rx.Observable 它将订阅 http post observable 完成事件。
@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)});
关于angular - 如何创建一个新的Observable,它订阅了angular2中http.post方法返回的Observable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31718807/