Angular通过服务获取存储数据

前端之家收集整理的这篇文章主要介绍了Angular通过服务获取存储数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

之前讲过angular可以通过可观察者对象在非父子组件之间进行数据的实时传递,此外angular可以通过服务存储临时数据在不同组件之间传递。

首先在app.service.ts定义一个变量inputData,以及存储和获取方法

  1. // app.component.service
  2. import { Injectable } from '@angular/core';
  3.  
  4. @Injectable()
  5. export class AppService {
  6.  
  7. private inputData: string;
  8.  
  9. constructor() { }
  10.  
  11. setInputValue(value) {
  12. this.inputData = value;
  13. }
  14.  
  15. getInputValue() {
  16. return this.inputData;
  17. }
  18.  
  19. }
  20.  
  21. // app.component.html
  22. <one-child></one-child>
  23. <two-child></two-child>

在one-child组件注入app.service并调用方法存储

  1. // one-child.component.html
  2. <div>
  3. one-child works!
  4. <input type="text" [(ngModel)]="oneChild" >
  5. <button (click)="saveDate()" >存储</button>
  6. </div>
  7.  
  8. // one-child.component.ts
  9. import { Component } from '@angular/core';
  10. import { AppService } from '../app.service'
  11.  
  12. @Component({
  13. selector: 'one-child',templateUrl: './one-child.component.html',styleUrls: ['./one-child.component.scss']
  14. })
  15. export class OneChildComponent {
  16.  
  17. oneChild;
  18. constructor(
  19. private appService: AppService
  20. ) { }
  21.  
  22. // 存储oneChild
  23. saveDate() {
  24. this.appService.setInputValue(this.oneChild);
  25. }
  26.  
  27. }

在two-child组件里面获取数据并展示:

  1. // two-child.component.html
  2. <p >
  3. two-child works!
  4. <input type="text" [(ngModel)]="twoChild" >
  5. <button (click)="getDate()" >获取</button>
  6. </p>
  7.  
  8. // two-child.component.ts
  9. import { Component,OnInit } from '@angular/core';
  10. import { AppService } from '../app.service'
  11.  
  12. @Component({
  13. selector: 'two-child',templateUrl: './two-child.component.html',styleUrls: ['./two-child.component.scss']
  14. })
  15. export class TwoChildComponent implements OnInit {
  16.  
  17. twoChild;
  18.  
  19. constructor(
  20. private appService: AppService
  21. ) { }
  22.  
  23. ngOnInit() {
  24. }
  25. // 获取数据并赋值给twoChild
  26. getDate() {
  27. this.twoChild = this.appService.getInputValue();
  28. }
  29.  
  30. }

具体demo代码可以在下面地址下载,下载后运行npm install:
https://github.com/ldpliudong...

但是这种办法不能实时数据更新,需要每次点击才能获取,此时可以通过以下方法进行:
1.将服务里面定义的数据设置为public,这样才能在其它组件之间调用该变量:

  1. //private inputData: string;
  2. public inputData: string;

2.在two-child组件html模板里面直接通过服务获取数据:

  1. <p >
  2. two-child works!
  3. <!-- <input type="text" [(ngModel)]="twoChild" > -->
  4. <input type="text" [(ngModel)]="appService.inputData" >
  5. <button (click)="getDate()" >获取</button>
  6. </p>

此外在html里面调用服务,需要在ts的constructor的注入里面设置为protected或者public:

  1. constructor(
  2. private appService: AppService
  3. public appService: AppService
  4. ) { }

这样,在one-child里面点击存储的时候,two-child就会同时更新~

猜你在找的Angularjs相关文章