且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用路由在Angular 2应用程序之间共享数据?

更新时间:2023-11-22 19:02:46

您可以通过以下方式访问父组件的路由参数:

You can access the parent component's route params with:

this.route.parent.params.subscribe(params => ....);

您还可以执行共享服务,其中每个组件都会更新其在服务中的价值,以供其他组件订阅.一个基本的示例如下所示:

You can also do a shared service where each component updates it's value in the service for others to subscribe to. A basic example would look like this:

import { Injectable } from '@angular/core';

import { BehaviorSubject } from 'rxjs/BehaviorSubject';


@Injectable()
export class SharedService {

  private _sharedDataSource = new BehaviorSubject<MyModel>(<MyModel>{});
  sharedData$ = this._sharedDataSource.asObservable();

  constructor() { }

  updateSharedData(data: MyModel) {
     this._sharedDataSource.next(data);
  }

}

A BehaviorSubject采用默认值,并确保可观察对象始终发出值.组件可以调用updateSharedData函数来更新数据,并订阅sharedData$以在发生更改时获取更新的值.

A BehaviorSubject takes a default value and ensure that the observable always emits a value. Components can call the updateSharedData function to update data and subscribe to sharedData$ to get updated value when something changes.

希望有帮助.