Angular通过服务获取存储数据
发布时间:2020-12-17 08:22:44 所属栏目:安全 来源:网络整理
导读:之前讲过angular可以通过可观察者对象在非父子组件之间进行数据的实时传递,此外angular可以通过服务存储临时数据在不同组件之间传递。 首先在app.service.ts定义一个变量inputData,以及存储和获取方法: // app.component.serviceimport { Injectable } fr
之前讲过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: 但是这种办法不能实时数据更新,需要每次点击才能获取,此时可以通过以下方法进行: //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就会同时更新~ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- twitter-bootstrap – 用razor和twitter bootstr
- Scala:有没有理由喜欢`filter map` over`collec
- Scala:我可以使用工厂方法重现匿名类创建吗?
- twitter-bootstrap – Bootstrap:我需要许可证来
- 扩展的几个应用 、 vim编辑技巧 、 发布网络YUM源
- 翻译:使用 Redux 和 ngrx 创建更佳的 Angular 2
- bash – 从后台进程获取PID作为另一个用户运行
- powershell 中常用cmd,unix命令(get-alias)
- 如何将一个glob表达式赋给一个变量在Bash脚本?
- AngularJS 用promises和$q处理异步调用
热点阅读