【问题标题】:Angular 2 routing refreshing parentAngular 2路由刷新父
【发布时间】:2018-01-22 10:18:01
【问题描述】:

在我的 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 });

【问题讨论】:

  • 你使用的是路线快照,还是可观察路线?
  • ngOnInit() { this.route.params .switchMap((params: Params) => this._aoService.getAOById(params["ao_id"])) .subscribe(selected => { (this .selectedAo = selected), this.setFormValues(); }); // }
  • 你在使用数据解析器吗?
  • 我在我的服务组件中使用 observable:updateAO(ao: AppelOffre): Observable { const headers = new Headers(); const options = new RequestOptions({ headers: headers });返回 this.http .put(this.updateAoUrl, ao, options) .map(success => success.status) .catch(this.handleError); }

标签: angular routing


【解决方案1】:

您需要一个更永久的流,以便当组件订阅status$ observable 时,它​​们会在更新发生时获得更新的值(来自 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$ observable 返回数据而不是状态码,它会更有用。但这取决于你。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-01
    • 2017-10-06
    • 1970-01-01
    • 2019-02-08
    • 2019-01-01
    • 2017-07-27
    • 2016-11-06
    • 1970-01-01
    相关资源
    最近更新 更多