在我的 Angular 应用程序中,我使用相对路由在组件之间导航。我有一个显示项目列表的父组件和一个用于编辑该组件的子组件。问题是,当我编辑一个项目并导航回以显示整个列表时,我必须刷新页面才能看到修改。
const aoRoutes: Routes = [
{
path: "",
redirectTo: "/ao/list",
pathMatch: "full"
},
{
path: "ao",
component: AppelOffreComponent,
children: [
{
path: "list",
component: ListAoComponent,
children: [
{
path: "edit/:ao_id",
component: EditAoComponent
},
..
];
我的组件是:
this._aoService
.updateAO(appelOffre)
.subscribe(success => {
this.statusCode = success;
this.loading = false;
}, error => (this.statusCode = error));
this.router.navigate(["../../"], { relativeTo: this.route });
您需要
一个更永久的流,以便当组件订阅可观察status$
时,它们在更新发生时获得更新的值(来自 http 调用(。该shareReplay
确保即使是迟到的订阅者也能收到有关事件的通知。
例如:
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/switchMap';
export class AoService {
status$: Observable<number>;
_status: Subject<AppelOffre>;
constructor(private http: HttpClient) {
this._status = new Subject<AppelOffre>();
this.status$ = this._status.switchMap(t=> {
const headers = new Headers();
const options = new RequestOptions({ headers: headers });
return this.http.put(this.updateAoUrl, ao, options)
.map(success => success.status).catch(this.handleError);
}).shareReplay(1);
}
update(ao: AppelOffre) {
this._status.next(ao);
}
}
使用此解决方案,您只需订阅状态事件并调用更新:
status: number;
constructor(private aoService: AoService) {
this.aoService.status$.subscribe(t=> {
this.status = t;
});
this.aoService.update();
}
您只需在一个地方拨打update()
。如果status$
可观察返回的数据而不是状态代码,则会更有用。但这取决于你。