如何在angular应用程序4、5或6中将数据从一个组件传递到另一个组件或调用函数。假设我有两个或更多组件的父组件。
发布于 2018-06-21 19:42:49
这里的第一件事是创建一个服务组件,如下所示:
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);
}
}下一步是设置父组件订阅数据服务,如下所示。
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.");
}
}在此之后,每个其他组件都可以传递/更改值,您的父组件将获取这些更改并执行您的逻辑。
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);
}
}发布于 2018-06-21 19:44:07
您可以为此创建一个服务。服务中的数据在所有组件之间共享。您可以将所有数据和函数移动到特定服务并调用该服务。例如:
constructor(private myservice: MyService){};.ts
this.myservice.myfunc();
this.myservice.mydata;.html
{{myservice.mydata}}https://stackoverflow.com/questions/50967216
复制相似问题