我有两个独立的组件; 一个包含选择搜索框的标题组件,stats组件根据选择框的值显示结果,我想知道一旦选择框改变是否可以刷新结果,我想到使用LocalStorage但它似乎是一个懒惰的解决方案.
SrA*_*Axi 30
使用共享服务:
服务:
@Injectable()
export class MyService {
myMethod$: Observable<any>;
private myMethodSubject = new Subject<any>();
constructor() {
this.myMethod$ = this.myMethodSubject.asObservable();
}
myMethod(data) {
console.log(data); // I have data! Let's return it so subscribers can use it!
// we can do stuff with data if we want
this.myMethodSubject.next(data);
}
}
Run Code Online (Sandbox Code Playgroud)
Component1(发件人):
export class SomeComponent {
public data: Array<any> = MyData;
public constructor(private myService: MyService) {
this.myService.myMethod(this.data);
}
}
Run Code Online (Sandbox Code Playgroud)
Component2(接收器):
export class SomeComponent2 {
public data = {};
public constructor(private myService: MyService) {
this.myService.myMethod$.subscribe((data) => {
this.data = data; // And he have data here too!
}
);
}
}
Run Code Online (Sandbox Code Playgroud)
最好的方法是将数据发送到组件。
使用@input属性将数据发送到控制器。然后实现ngOnChanges并执行函数以加载数据。
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'second-component',
})
@Injectable()
export class SecondComponent implements OnChanges {
@Input()
selectValue: string;
ngOnChanges(changes: SimpleChanges) {
if (changes['selectValue']) {
//call your function to load the data
}
}
}
Run Code Online (Sandbox Code Playgroud)
用途
<second-component [selectValue]="bindYourValue"></second-component>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26186 次 |
| 最近记录: |