我如何得到了传递,数据或角应用程序中调用从一个组件的功能,另外4,5或6。比方说,我有我的父组件与两个或多个组件。
Answer 1:
您创建的服务。 在一个服务中的数据的所有组件之间共享。 您可以将所有数据和功能移动到特定的服务,并调用该服务。 例如:
constructor(private myservice: MyService){};
.TS
this.myservice.myfunc();
this.myservice.mydata;
html的
{{myservice.mydata}}
Answer 2:
这里的第一件事就是创建这样一个服务组件:
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);
}
}
文章来源: Angular 5, 6 components communication using rxjs