現(xiàn)在前端任意一款主流框架因?yàn)槎际悄K化結(jié)構(gòu)抑钟,所以都繞不開組件或者模塊之間通信德迹。大部分時(shí)間我們說解決組件之間通信是子組件向父?jìng)髦的炙猓话阕咏M件的值會(huì)繼承父組件寺枉,父變子跟著變,但子變父不會(huì)變绷落。
那么今天就來看看在angular4中如何使用Observable來實(shí)現(xiàn)子向父?jìng)髦道焉粒?dāng)然它也可以在任意兩個(gè)組件或多個(gè)組件中傳值。這個(gè)方案比官方文檔提供的單純的父子組件關(guān)系的解決方案應(yīng)用范圍更廣砌烁。
實(shí)現(xiàn)一個(gè)消息通知demo筐喳,在任何一個(gè)組件調(diào)用顯示消息方法,在根組件就會(huì)顯示3秒的消息提示框往弓。
文件結(jié)構(gòu)
- 父組件:
app.component.ts疏唾、app.component.html
- 子組件:
home.component.html、home.component.html
- 服務(wù):
shared.service.ts
關(guān)鍵方法
-
Observable.subscribe()
用于訂閱發(fā)送可觀察對(duì)象的消息 -
Subject.next()
用于向觀察者對(duì)象發(fā)送消息函似,然后將其發(fā)送給改觀察者的所有訂閱者 -
Subject.asObservable()
返回一個(gè)可觀察對(duì)象槐脏,一旦值變化,便會(huì)同時(shí)向它的訂閱者更新消息撇寞。
shared.service公共服務(wù)
//shared.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class SharedService {
private msg = new Subject<any>();
//發(fā)送消息
sendMessage(message: string) {
this.msg.next(message);
}
//清除消息
clearMessage() {
this.msg.next();
}
//獲取消息
getMessage(): Observable<any> {
return this.msg.asObservable();
}
}
app父組件獲取消息
<!--app.component.html-->
<p-growl [(value)]="alertMsg"></p-growl>
//app.component.ts
public alertMsg: Array<object>;
constructor(private sharedService: SharedService) {}
ngOnInit() {
//消息提示 從service獲取消息內(nèi)容
this.sharedService.getMsg().subscribe(value => {
this.alertMsg = value;
})
}
home子組件發(fā)送消息
<!--home.component.html-->
<button (click)="sendMessage()">Send Message</button>
//home.component.ts
constructor(private sharedService: SharedService) {}
public sendMessage() {
//發(fā)送消息
this.sharedService.sendMessage('顯示成功');
}
至此顿天,關(guān)于子組件向父組件傳值就到這里了,主要是學(xué)會(huì)利用Observable來傳值蔑担,需要注意一點(diǎn)的是最新版的rxjs不支持該方式牌废,應(yīng)該有其他方法代替,這個(gè)用的rxjs版本是V5.1.0啤握,是可以使用的鸟缕。