首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用rxjs的Angular 5,6组件通信

使用rxjs的Angular 5,6组件通信
EN

Stack Overflow用户
提问于 2018-06-21 19:16:49
回答 2查看 492关注 0票数 0

如何在angular应用程序4、5或6中将数据从一个组件传递到另一个组件或调用函数。假设我有两个或更多组件的父组件。

EN

回答 2

Stack Overflow用户

发布于 2018-06-21 19:42:49

这里的第一件事是创建一个服务组件,如下所示:

代码语言:javascript
复制
import { Injectable } from '@angular/core';
import { BehaviorSubject, Subject, Observable } from 'rxjs';

@Injectable()
export class DataService {

    constructor() { }

    private data = new BehaviorSubject<string>("Home");

    //this is what your components subsribes to
    currentData() : Observable<string> {
       return this.data.asObservable();
    }

    //this function allows you to change the value to be accessed by other components
    changeData(message: string) {
      this.data.next(message);
    }

}

下一步是设置父组件订阅数据服务,如下所示。

代码语言:javascript
复制
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    //component member variable to be changed on value change detection
    message = "";

    //here you'll inject in your component constructor the service declaration
    constructor(private data: DataService) {

    }

    ngOnInit(){
        this.data.currentData().subscribe((message:string) => {
            //here i log changes detected on the console
            console.log("i have changed");
            //you can perform any call or action here e.g
            //update a variable
            this.message = message;
            //or call a function
            canCall();
        });
    }

    canCall(){
        console.log("i am called.");
    }
}

在此之后,每个其他组件都可以传递/更改值,您的父组件将获取这些更改并执行您的逻辑。

代码语言:javascript
复制
import { Component, OnInit } from '@angular/core';
import { DataService } from './../data.service';

@Component({
    selector: 'app-productreview',
    templateUrl: './productreview.component.html',
    styleUrls: ['./productreview.component.css']
})
export class ProductreviewComponent implements OnInit {

    //here we inject the data service just like before
    constructor(private data: DataService) { }

    //optional
    ngOnInit(){
        this.data.currentData().subscribe((message:string) => this.currentAction = message);
    }

    //this where we change the data
    changeData(option: string = "New Data"){
        this.data.changeData(option);
    }

}
票数 2
EN

Stack Overflow用户

发布于 2018-06-21 19:44:07

您可以为此创建一个服务。服务中的数据在所有组件之间共享。您可以将所有数据和函数移动到特定服务并调用该服务。例如:

代码语言:javascript
复制
constructor(private myservice: MyService){};

.ts

代码语言:javascript
复制
this.myservice.myfunc();
this.myservice.mydata;

.html

代码语言:javascript
复制
{{myservice.mydata}}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50967216

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档