Resolve 不会等待 API 调用完成才落入函数末尾

Resolve doesn't wait for API call to complete before falling to end of function

我正在制作一个 Angular 4 网络应用程序。我有一个页面需要在显示之前等待数据,所以我正在使用 resolve。首先 resolve 检查数据是否在存储中可用,如果是则检查路由中的 id 和数据是否匹配,如果不匹配,则从 API 中检索数据,最后如果数据在存储中不存在则检索它来自 API。但是,如果进行了 API 次调用,该函数总是会结束。我做错了什么?

resolve(route: ActivatedRouteSnapshot): Observable<PDataInterface>
{
  const routeID = route.params.id;
  // get data from storage
  this.getData();
  if (!!this.pData) {
    if (this.pData.id == routeID) {
      return Observable.of(this.pData);
    } else {
      this.API.getInfo(this.routeID).subscribe((data) => {
        this.pData = data;
        return Observable.of(this.pData);
      });
    }
  } else {
    this.API.getInfo(this.pData.id).subscribe((data) => {
      this.pData = data;
      return Observable.of(this.pData);
    });
  }
  // function always comes here if API calls are made
  console.log("failed resolve");
  this.router.navigate(['/dashboard']);
}

api.ts

getInfo(id) {
    const URL = `${this.API}/paintline/${id}`;
    return this.refreshToken()
      .flatMap(() => this.authHttp.get(URL, this.headers))
      .map((response: Response) => response.json().data)
      .share()
      .catch(this.handleError);
}

这是getInfo()中调用的refreshToken()。如果在向后端发出请求之前过期,它会刷新我的 JWT 令牌

refreshToken(): Observable<any>
{
  const URL = `${this.API}/refresh?token=${this.token}`;
  if (this.jwtHelper.isTokenExpired(this.token)) {
    return this.authHttp.get(URL)
      .map((rsp) =>
        {
          this.setToken(rsp.json().token);
          this.authNotifier.next(true);
          return rsp.json().token;
        },
        err =>
        {
          this.authNotifier.next(false);
          this.logout();
          console.log(err);
        })
      .share();
  }
  else { return Observable.of(this.token); }
}

app.module.ts

RouterModule.forRoot([
{
        {
          path: 'details',
          component: PDetailsComponent,
          resolve: {pData: PResolverService}
        },
}]

当您订阅 api 时,您的 API 会被触发,但其余解析代码会继续执行。这就是它不断到达您的 console.log("failed resolve"); 的原因。相反,您应该 return api observable 并让解析器执行订阅。

resolve(route: ActivatedRouteSnapshot): Observable<PDataInterface>
{
    const routeID = route.params.id;
    // get data from storage
    this.getData();
    if (!!this.pData) {
        if (this.pData.id == routeID) {
            return Observable.of(this.pData);
        } else {
            return this.API.getInfo(this.routeID);
        }
    } else {
        return this.API.getInfo(this.pData.id);
    }
}