Angular通过服务获取存储数据

发布时间:2019-06-12 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Angular通过服务获取存储数据脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

之前讲过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就会同时更新~

脚本宝典总结

以上是脚本宝典为你收集整理的Angular通过服务获取存储数据全部内容,希望文章能够帮你解决Angular通过服务获取存储数据所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。