如何在Angular 4.x中替换Angular 2.x中的“.then”

时间:2017-08-29 20:53:40

标签: angular

我在版本2.x中有一个Angular项目,我想将其更新到版本4.x。

 loginUser(): void {
    console.log("login.component.loginUser called");

    this.loginService.getTokenInfo(this.userCredentials.userName, this.userCredentials.password)
      .then(tokenInfo => this.tokenInfo = tokenInfo)
      .then(tokenInfo => myGlobals.authToken = tokenInfo.token)
      .then(() => {
        this.redirectToFuPage();
      });
  }

如何将其更改为适用于版本4.x?

我的服务方法如下。

getTokenInfo(userName: string, password: string): Promise<TokenInfo> {
    console.log("login.service.getTokenInfo called");
    this.credentials = JSON.stringify({userName: userName, password: password});

    return this.http.post(this.loginUrl, this.credentials, this.options)
               .toPromise()
               .then(res => res.json() as TokenInfo)
               .catch(this.handleError);
  }
然后

属性在observable上不存在。

之前它对我有用。

1 个答案:

答案 0 :(得分:0)

更换&#34;然后&#34;用&#34; map&#34;当我返回一个Observable并替换&#34;然后&#34;用&#34;订阅&#34;一旦我得到了observable修正了这个问题。

getTokenInfo(userName: string, password: string): Observable<TokenInfo> {
    this.credentials = JSON.stringify({userName: userName, password: password});

    return this.http.post(this.loginUrl, this.credentials, this.options)
               .map(res => res.json() as TokenInfo)
}

这是loginUser()方法

loginUser(): void {
    this.loginService.getTokenInfo(this.user.userName, this.user.password)
        .subscribe(response => {
           this.tokenInfo = response;
           myGlobals.authToken = this.tokenInfo.token;
           this.redirectToFuPage();
        })
}