之前讲过angular可以通过可观察者对象在非父子组件之间进行数据的实时传递,此外angular可以通过服务存储临时数据在不同组件之间传递。
首先在app.service.ts定义一个变量inputData,以及存储和获取方法:
// 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并调用方法存储
// 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组件里面获取数据并展示:
// 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...
但是这种办法不能实时数据更新,需要每次点击才能获取,此时可以通过以下方法进行:
1.将服务里面定义的数据设置为public,这样才能在其它组件之间调用该变量:
//private inputData: string; public inputData: string;
2.在two-child组件html模板里面直接通过服务获取数据:
<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:
constructor( private appService: AppService public appService: AppService ) { }
这样,在one-child里面点击存储的时候,two-child就会同时更新~
原文链接:https://www.f2er.com/angularjs/144926.html