以前講過angular能夠經過可觀察者對象在非父子組件之間進行數據的實時傳遞,此外angular能夠經過服務存儲臨時數據在不一樣組件之間傳遞。css
首先在app.service.ts定義一個變量inputData,以及存儲和獲取方法:html
// app.component.service import { Injectable } from '@angular/core'; @Injectable() export class AppService { private inputData: string; constructor() { } setInputValue(value) { this.inputData = value; } getInputValue() { return this.inputData; } } // app.component.html <one-child></one-child> <two-child></two-child>
在one-child組件注入app.service並調用方法存儲git
// one-child.component.html <div> one-child works! <input type="text" [(ngModel)]="oneChild" > <button (click)="saveDate()" >存儲</button> </div> // one-child.component.ts import { Component } from '@angular/core'; import { AppService } from '../app.service' @Component({ selector: 'one-child', templateUrl: './one-child.component.html', styleUrls: ['./one-child.component.scss'] }) export class OneChildComponent { oneChild; constructor( private appService: AppService ) { } // 存儲oneChild saveDate() { this.appService.setInputValue(this.oneChild); } }
在two-child組件裏面獲取數據並展現:github
// two-child.component.html <p > two-child works! <input type="text" [(ngModel)]="twoChild" > <button (click)="getDate()" >獲取</button> </p> // two-child.component.ts import { Component, OnInit } from '@angular/core'; import { AppService } from '../app.service' @Component({ selector: 'two-child', templateUrl: './two-child.component.html', styleUrls: ['./two-child.component.scss'] }) export class TwoChildComponent implements OnInit { twoChild; constructor( private appService: AppService ) { } ngOnInit() { } // 獲取數據並賦值給twoChild getDate() { this.twoChild = this.appService.getInputValue(); } }
具體demo代碼能夠在下面地址下載,下載後運行npm install:
https://github.com/ldpliudong...npm
可是這種辦法不能實時數據更新,須要每次點擊才能獲取,此時能夠經過如下方法進行:
1.將服務裏面定義的數據設置爲public,這樣才能在其它組件之間調用該變量:app
//private inputData: string; public inputData: string;
2.在two-child組件html模板裏面直接經過服務獲取數據:this
<p > two-child works! <!-- <input type="text" [(ngModel)]="twoChild" > --> <input type="text" [(ngModel)]="appService.inputData" > <button (click)="getDate()" >獲取</button> </p>
此外在html裏面調用服務,須要在ts的constructor的注入裏面設置爲protected或者public:spa
constructor( private appService: AppService public appService: AppService ) { }
這樣,在one-child裏面點擊存儲的時候,two-child就會同時更新~code