加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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:
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就会同时更新~

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读