对于这个问题,您可以使用rxjs SubjectBehaviour.make随机服务,如下所示
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class RandomService {
private msgsource = new BehaviorSubject<string>('this is the default');
telecast = this.msgsource.asObservable();
constructor() { }
editMsg(newmsg) {
this.msgsource.next(newmsg);
}
}
这个组件想要发送数据,需要声明该服务方法并将数据发送到该方法中,无论该服务方法在何处被调用,数据都会反映出来。
import { Component, OnInit, Input } from '@angular/core';
import { RandomService } from '../random.service';
@Component({
selector: 'app-first',
templateUrl: './first.component.html',
styleUrls: ['./first.component.css']
})
export class FirstComponent implements OnInit {
@Input('incomingmsg') newrandmsg: string;
message: string;
editedmsg: string;
constructor(private someserv: RandomService) { }
ngOnInit() {
}
editthemsg() {
this.someserv.editMsg(this.editedmsg);
}
}
现在在ngOnInit中接收该数据到头部组件,以便检测该服务方法中任何值的更改。
头部组件。
ngOnInit() {
this.someserv.telecast.subscribe(message => this.message = message)
}
每当随机服务发生任何更改时,它将检测并将数据显示到标题组件中。