具有多个数据的Angular 5共享服务
发布时间:2020-12-17 17:24:04 所属栏目:安全 来源:网络整理
导读:在互联网上,我找到了如何与服务共享数据的示例: import { Injectable } from '@angular/core';import {Subject} from 'rxjs/Subject';import {Observable} from 'rxjs/Observable';@Injectable()export class DataService { private subject = new Subjecta
在互联网上,我找到了如何与服务共享数据的示例:
import { Injectable } from '@angular/core'; import {Subject} from 'rxjs/Subject'; import {Observable} from 'rxjs/Observable'; @Injectable() export class DataService { private subject = new Subject<any>(); sendData(phone: any) { this.subject.next(phone); } clearData() { this.subject.next(); } getData(): Observable<any> { return this.subject.asObservable(); } } 然后我们订阅更改 subscription: Subscription; this.subscription = this.dataService.getData() .subscribe(data => { this.someData= data; }); 好的,这工作正常.但是,如果我想分享多个元素?为每个元素复制此代码似乎是不合理的,只更改名称.但我找不到任何抽象的解决方案.也许使用带有名称和数据本身的地图,但我无法理解如何在这种情况下订阅更改以及应该如何看待服务. 解决方法
要实现此目的,您可以将所有相关值放入(行为)主题中此对象的包装器对象中.每个订阅者更改其感兴趣的个人价值的内容,然后将整个包装器写回.
例如 假设您将所有定义的模型放入models.ts中.这是包装器. export class MyWrapper { constructor( public value1?: string,public value2?: number,public value3?: boolean ){} } 然后将此包装器模型导入您的服务和所有订阅服务器 import { Injectable } from '@angular/core'; import {Subject} from 'rxjs/Subject'; import {Observable} from 'rxjs/Observable'; import { MyWrapper } from '../models/models'; @Injectable() export class DataService { private subject = new Subject<MyWrapper>(); sendData(wrapper: MyWrapper) { this.subject.next(wrapper); } clearData() { this.subject.next(); } getData(): Observable<MyWrapper> { return this.subject.asObservable(); } } 在其中一个订阅者中,无论是服务,指令还是组件,您都可以操纵该值.只是一个例子!如何来回处理包装有许多不同的方法. import { MyWrapper } from '../models/models'; private localWrapper: MyWrapper; constructor( private dataService: DataService ){} ngOnInit(): void { this.dataService.getData().subscribe(wrapper => { this.localWrapper = wrapper; }); } // The wrapper in your service gets replaced and all subscribers // get a fresh version of all contained values. This way you // could exchange hundreds of values with only one set of methods // and a single (Behavior)Subject. private saveValue1(value: string): void { localWrapper.value1 = value; this.dataService.sendData(localWrapper); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- 有谁知道一个轻的Vim方案,使编码更可读和愉快?
- 架设用Webservice实现文件上传功能CentOS服务器(
- twitter-bootstrap – Twitter Bootstrap Carous
- twitter-bootstrap – 什么是Vanilla Bootstrap?
- 使用Angular 2的Jade / Pug – 如何解决与#synta
- 在Angular2中使用ngFor进行多次转换
- scala – Spray routing:如何响应不同的内容类型
- Bootstrap的Refresh Icon也spin起来
- scala – 这是liftweb TimeHelpers的一个错误:6
- regex – 在字符串与bash文本实用程序匹配后计算
热点阅读