Int*_*eep 9 javascript typescript angular-services angular-components angular
我的目标是将数据从Angular组件发送到服务并使用服务方法来处理它.例:
export class SomeComponent {
public data: Array<any> = MyData;
public constructor(private myService: MyService) {
this.myService.data = this.data;
}
}
Run Code Online (Sandbox Code Playgroud)
和服务:
@Injectable()
export class TablePageService {
public data: Array<any>;
constructor() {
console.log(this.data);
// undefined
}
}
Run Code Online (Sandbox Code Playgroud)
获取数据是不确定的.如何使其工作?
SrA*_*Axi 14
如果服务和组件之间的交互可能是:
服务:
@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: Array<any> = MyData;
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)
说明:
MyService管理着data.data如果你愿意,你仍然可以做一些事情,但最好还是留下来Component2.
基本上MyService接收data从Component1并将其发送给谁订购了该方法myMethod().
Component1正在发送data给MyService他,而这就是他所做的一切.
Component2订阅,myMethod()所以每次myMethod()被调用,Component2将听取并得到任何myMethod()返回.
| 归档时间: |
|
| 查看次数: |
17228 次 |
| 最近记录: |