【发布时间】:2017-09-29 06:28:48
【问题描述】:
我有两个独立的组件,一个组件与另一个组件没有关系,但我的目的是与这些组件通信,我知道与发射器共享服务可以在父子组件之间共享数据如果组件之间没有关系但是必须根据其他组件更改一个组件 例如:
import {Component,bind,CORE_DIRECTIVES,OnInit} from 'angular2/core';
import {MainComponent} from 'src/MainComponent';
import {SharedService} from 'src/shared.service';
@Component({
selector: 'my-app',
directives:[MainComponent],
template: `<h1>AppComponent {{onMain}}</h1>
<div *ngIf="onMain == false">
Hello
<br> __________________________________<br>
</div>
})
export class AppComponent implements OnInit {
onMain: Boolean;
constructor(ss: SharedService) {
this.onMain = false;
this.ss = ss;
}
ngOnInit() {
this.subscription = this.ss.getMessage()
.subscribe(item => this.onMain=item);
}
}
第二部分
import {Component,bind,CORE_DIRECTIVES} from 'angular2/core';
import {SharedService} from 'src/shared.service';
@Component({
selector: 'main-app',
template: `<h1> MainComponent</h1>
<button (click)="changeName()">Change Name</button>
`
})
export class MainComponent {
constructor(ss: SharedService) {
this.ss = ss;
}
changeName() {
this.ss.sendMessage(true);
}
}
共享服务
import { Subject } from 'rxjs/Subject';
@Injectable()
export class LandingService {
private subject = new Subject<any>();
sendMessage(message: any) {
this.subject.next({ text: message });
}
clearMessage() {
this.subject.next();
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
问题是两个组件不是相互关联的,它们在两条不同的路线上运行,但是从第二个组件单击我想更改 第一个组件中声明的 OnMain 的值 strong> 基本上我想更新组件或向 第一个组件 发送一个值已更改的信号并相应地更新它。
我们将不胜感激它可能或没有帮助
【问题讨论】: