2

我有一个组件可以在加载时解析来自路由的数据。

我的挑战是,每当组件呈现的数据发生更改时,除非我刷新页面或切换到另一条路线并返回,否则组件不会更新。

我理解这是因为只有在访问路线时才会解析数据。

有没有办法让我可以订阅已解析数据的更改?

以下是相关的代码块。

路线.ts

{
    path: 'user-information',
    component: UserInformationComponent,
    resolve: { userData: UserDataResolver }
}

解析器.ts

@Injectable()
export class UserDataResolver implements Resolve<any> {

  constructor(
    private userService: UserService
  ) {};

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<IUser> {
   return this.userService.currentUser().first();
  };
};

用户.component.ts

loadUserData() {
  this.route.data.subscribe(
    data  => this.userData = data,
    error => this.updateForm.disable()
  );
};
4

1 回答 1

1

Resolvers only allow to return a single value or object. You should be able to wrap this.userService.currentUser() in a Promise (or another Observable) and return that:

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<IUser> {
 return Promise.resolve(this.userService.currentUser());
};

You should then be able to 'rehydrate' your Observable in the component's code:

loadUserData() {
  this.route.data
    .mergeMap(data => userData)
    .subscribe(
      userData => this.userData = userData,
      error => this.updateForm.disable()
    );
  };
}

I can't test it right away, but I'm confident this works.

于 2017-08-08T17:48:39.937 回答