简体   繁体   English

如何订阅已解析路线数据的更改-Angular 2

[英]How to subscribe to changes on resolved route data - Angular 2

I have a component that resolves data from a route when loaded. 我有一个组件,可以在加载时解析路由中的数据。

My challenge is, whenever the data being rendered by the component changes, the component doesn't get updated unless I refresh the page, or switch to another route and back. 我的挑战是,每当组件渲染的数据发生更改时,除非刷新页面或切换到其他路线再返回,否则组件不会得到更新。

I understand this is because the data only gets resolved when the route is visited. 我了解这是因为仅在访问路线时才解析数据。

Is there a way around this such that I can subscribe to changes on the resolved data ? 有没有办法解决这个问题,以便我可以订阅已解析数据的更改?

Below are the relevant blocks of code. 以下是相关的代码块。

routes.ts routes.ts

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

resolver.ts resolver.ts

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

  constructor(
    private userService: UserService
  ) {};

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

user.component.ts user.component.ts

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

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: 您应该能够将this.userService.currentUser()包装在Promise(或另一个Observable)中并返回:

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: 然后,您应该能够在组件的代码中“补充水分”您的Observable:

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. 我无法立即对其进行测试,但是我相信这是可行的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM