使用共享服务:
原文链接:https://www.f2er.com/angularjs/140882.html服务:
@Injectable() export class MyService { myMethod$: Observable<any>; private myMethodSubject = new Subject<any>(); constructor() { this.myMethod$= this.myMethodSubject.asObservable(); } myMethod(data) { console.log(data); // I have data! Let's return it so subscribers can use it! // we can do stuff with data if we want this.myMethodSubject.next(data); } }
Component1(发件人):
export class SomeComponent { public data: Array<any> = MyData; public constructor(private myService: MyService) { this.myService.myMethod(this.data); } }
Component2(接收器):
export class SomeComponent2 { public data = {}; public constructor(private myService: MyService) { this.myService.myMethod$.subscribe((data) => { this.data = data; // And he have data here too! } ); } }