我想念一些事情,完全掌握承诺的概念。
我尝试实现这一点:一旦我的http返回就调用一个函数,如下所示
onSubmit(event: any) {
this.submitted = true;
event.preventDefault();
this.si
.signIn(this.emailAddress, this.password, this.keepSignedIn)
.toPromise()
.next((res:any) => {
this.router.navigate(['dashboard']);
});
}
但得到了错误:
this.si
.signIn(this.emailAddress, this.password, this.keepSignedIn)
.toPromise is not a function.':
在服务中,我按如下方式写了我的电话;
signIn(emailAddress: string, password: string, keepSignedIn: boolean): Promise<any> {
console.log("SigninService, emailaddress="+emailAddress);
console.log("SigninService, password="+password);
const auth = this.buildAuthToken(emailAddress, password, keepSignedIn);
const headers = this.getHeaders();
console.log("SigninService, headers="+JSON.stringify(headers));
const url = 'http://dev-user.zeens.ws/api/v1/me';
return this.http.get(url, {headers: headers})
.toPromise()
.then(response => {
console.log("response="+JSON.stringify(response.json()));
this.user = response.json().result;
console.log("response="+JSON.stringify(this.user));
localStorage.setItem('user', JSON.stringify(this.user));
return this.user;
/*
console.log("signin="+JSON.stringify(response.json().data));
return response.json().data;
*/
})
.catch(this.handleError);
}
答案 0 :(得分:2)
return this.http.get(url, {headers: headers})
.toPromise()
.then(response => {
...
})
.catch(this.handleError);
在您的服务中,您已使用toPromise
。
在您编写时,您的函数具有以下定义:
signIn(emailAddress: string, password: string, keepSignedIn: boolean): Promise<any>
然后你做:
this.si
.signIn(this.emailAddress, this.password, this.keepSignedIn)
.toPromise() // <---- PROBLEM
.next((res:any) => {
this.router.navigate(['dashboard']);
});
您可以尝试在承诺上应用toPromise
。
很奇怪,你为什么要把它转换为诺言?
你可以这样做:
signIn(emailAddress: string, password: string, keepSignedIn: boolean): Observable<any> {
...
return this.http.get(url, {headers: headers})
.map((response: Response) => {
this.user = response.json().result;
localStorage.setItem('user', this.user);
return this.user;
})
.catch(this.handleError);
}
onSubmit(event: any) {
this.submitted = true;
this.si
.signIn(this.emailAddress, this.password, this.keepSignedIn)
.subscribe((res:any) => {
this.router.navigate(['dashboard']);
});
// returning false is equivalent to event.preventDefault()
return false;
}
编辑:
为了定义地图,您需要导入它
在main.ts或仅加载一次的地方,添加以下内容:
import 'rxjs/add/operator/map';
例如,这是我的导入:
// rxjs operators
// see node_module/rxjs/Rxjs.js
// statics
import 'rxjs/add/observable/throw';
// operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/delay';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/let';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/withLatestFrom';
import 'rxjs/add/operator/combineLatest';
// observables
import 'rxjs/add/observable/empty';