大佬教程收集整理的这篇文章主要介绍了angular – 如何使用共享服务将数据从一个组件发送到另一个组件,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
app.component.ts
import { Component } from '@angular/core'; import { shareservice } from './share.service'; @Component({ SELEctor: 'my-app',template: ` <Hello></Hello> <button (click)="passData()"> Start </button> `,styleUrls: [ './app.component.css' ],providers:[shareservice] }) export class AppComponent { constructor(private service : shareservicE){} passData(){ this.service.send("Hello"); } }
Hello.component.ts
import { Component,Input } from '@angular/core'; import { shareservice } from './share.service'; import { Subscription } from 'rxjs/Subscription'; @Component({ SELEctor: 'Hello',template: `<h1>Hello!</h1>`,styles: [`h1 { font-family: Lato; }`],providers:[shareservice] }) export class HelloComponent { subscription: Subscription; constructor(private share : shareservicE){ this.subscription = share.subj$.subscribe(val=>{ console.log(val); }) } }
share.service.ts
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; @Injectable() export class shareservice{ private sub = new Subject(); subj$= this.sub.asObservable(); send(value: String) { this.sub.next(value); } }
我没有在控制台中获得价值.
这是工作演示:DEMO
@Component({ ..... providers: [shareservice] })
在这两个组件中,您将创建共享servcie的两个不同实例.
每个实例都不“了解”每个组件的数据.
提供模块级别,它将工作.
@NgModule({ .... providers: [shareservice] })
这样,您将服务作为单个实例注入到两个组件中,因此它们可以共享它,因为它们将共享数据.
见also
以上是大佬教程为你收集整理的angular – 如何使用共享服务将数据从一个组件发送到另一个组件全部内容,希望文章能够帮你解决angular – 如何使用共享服务将数据从一个组件发送到另一个组件所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。