我的变量虽然已传递值,但不会显示数据。 如果使用控制台,它将显示该值。我对棱角还很陌生,所以请忍受我。
export class Page2Component implements OnInit {
public person = {} as Person;
constructor(public broadCastService : BroadcastService) {
this.broadCastService.events.subscribe((e) => {
this.person.age =e.age;
this.person.name = e.name;
});
}
<div class="column-6">
<h2>This is the PAGE 2</h2>
<p>Message will be display here from first.html</p>
Name: {{person.name}}<br>
Age: {{person.age}}<br>
</div>
<div id="2"></div>
我的广播服务。
export class BroadcastService {
public events: Observable<any>;
private channel = new BroadcastChannel('test_channel');
constructor() {
this.events = new Observable ((observer) => {
//this.events = Observable.create(obs => {
this.channel.onmessage = ev => {
observer.next(ev.data);
}
this.channel.onmessageerror = ev => {
observer.error(ev);
}
});
}
public addPerson(person : any) {
this.channel.postMessage(person);
}
}
答案 0 :(得分:0)
在ngOnInit()
中而不是构造函数中调用函数。
export class Page2Component implements OnInit {
public person = {} as Person;
constructor(public broadCastService : BroadcastService) {
}
ngOnInit(){
this.broadCastService.events.subscribe((e) => {
this.person.age =e.age;
this.person.name = e.name;
});
}
答案 1 :(得分:0)
我要在这里a行,并假设onmessage
在角度区域之外运行。您可以通过记录NgZone.isInAngularZone()
响应来进行检查,如下所示:
this.channel.onmessage = ev => {
console.log('Is in zone:', NgZone.isInAngularZone()); // probably logs false
observer.next(ev.data);
}
问题是您需要使用addEventListener
方法来确保它在区域中运行。像这样:
this.channel.addEventListener('message', (ev) => {
console.log('Is in zone:', NgZone.isInAngularZone()); // should log true
observer.next(ev.data);
});
或强迫它在区域内运行(请确保将您的班级设为@Injectable()
):
@Injectable()
export class BroadcastService {
// ...
constructor(readonly ngZone: NgZone) {
// ...
this.channel.onmessage = ev => {
this.ngZone.run(() => {
console.log('Is in zone:', NgZone.isInAngularZone()); // should log true
observer.next(ev.data)
});
}
}
}