在使用Angular和Ionic完成功能之前,已成功解决了承诺

时间:2020-04-23 17:57:24

标签: angular typescript ionic4 es6-promise angular-promise

我创建了一个服务,该服务具有从API检索令牌的方法,该API在内部调用subscribe()。从组件调用此方法,它不返回Observable,而仅返回包含令牌的字符串。

然后,有另一种方法应在获得令牌后从组件中调用,但是,总是在另一个方法之前调用它。我什至尝试过在组件中使用async / await,但这没有用。

// api.service.ts
logIn() {
  if(!this.token) {  
    this.http.post(this.apiURL + "/token/", {username: "test", password: "test"}, options).subscribe(response => {
    if(response.status == 200) {
        this.body = response.body;
        this.token = "Token " + this.body.token;
        window.sessionStorage.setItem("TOKEN_KEY", this.token);
        console.log(this.token);
    }
  }
  return this.token;
}

如您所见,该方法仅返回令牌,因此我正在组件中创建一个Promise,一旦解决该问题,将调用getProduct()方法,但在令牌已经存在之前调用它。

// product.component.ts

async getLogin() {
  const resp = await this.apiService.logIn();
  console.log(resp);
}

getMenu() {
  this.apiService.getMenu().subscribe(resp => {
    console.log(resp);
});

constructor(private apiService: APIService) {
  this.getLogin().then(resp => {
    console.log('Called');
    // Call before the token has already been created!
    this.getMenu();
  });  
}

2 个答案:

答案 0 :(得分:0)

问题是您的函数logIn在异步调用this.token中设置了this.http.post的值,因此当您return this.token;时尚未分配它。您要早点回来。如果您想采用 Promise 方法,则logIn必须返回 Promise

async logIn() {
  if(!this.token) {  
    return this.http.post(this.apiURL + "/token/", {username: "test", password: "test"}, options)
      .toPromise()
      .then(response => {
        if(response.status == 200) {
            this.body = response.body;
            this.token = "Token " + this.body.token;
            window.sessionStorage.setItem("TOKEN_KEY", this.token);
            console.log(this.token);

            return this.token; // important to return the token here
        }
      }
  }
  return this.token;
}

请注意,我已将async关键字添加到logIn函数,将{{1}的subscribe更改为toPromise,与.then链接并添加了{{ 1}}。

希望有帮助。

答案 1 :(得分:0)

logIn()方法中,您应该返回Observable

logIn(): Observable<string> {
  return this.http
    .post(this.apiURL + "/token/", {username: "test", password: "test"}, options)
    .pipe(
        filter(response => response.status == 200),
        map(response => response.body.token),
        tap(token => {
           window.sessionStorage.setItem("TOKEN_KEY", `Token ${token}`);
        })
    );
}

然后在构造函数中

constructor(private apiService: APIService) {
    this.getLogin().subscribe(token => {
        console.log('Called');
        // Call before the token has already been created!
        this.getMenu();
    });  
}
相关问题