我有一項服務,試圖對給定組件的值進行水合。基本功能:
- 服務將接受一個組件到它的方法中
- 執行 HTTP 請求以檢索資料
- 資料決議后更新組件的@Input 變數
我在下面寫了一些偽代碼來詳細說明我要做什么。這有可能嗎?
服務方式:
public mapTo(component: any): void {
httpCall.then(result => {
component.inputVariable = result.data;
});
}
零件:
export SomeComponent {
@Input() inputVariable = null; // expecting this to be updated by the service
constructor(private modelService: ModelService) {
this.modelService.mapTo(SomeComponent);
}
}
uj5u.com熱心網友回復:
您想要做的是 Angular 世界中的一點反模式。
public mapTo(component: any): Observable<any>{
return httpCall.pipe(result => {
map(result => result.data)
});
}
在組件方面:
SomeComponent {
inputVariable = null; // expecting this to be updated by the service
constructor(private modelService: ModelService) {
this.modelService.mapTo().subscribe(result => this.inputVariable = result);
}
}
如果這不可能,您可以嘗試將組件實體注入服務。所以在你的服務檔案中
xxxxx.service.ts
Injectable()
export class Myservice{
constructor(@Inject(forwardRef(() => SaveComponent)) saveComponent){}
public mapTo(): Observable<any>{
return httpCall.pipe(result => {
map(result => this.saveComponent.inputVariable = result.data)
});
}
}
v3 - 傳遞組件實體
服務方式:
public mapTo(component: any): void {
httpCall.then(result => {
component.inputVariable = result.data;
});
}
零件:
export SomeComponent {
@Input() inputVariable = null; // expecting this to be updated by the service
constructor(private modelService: ModelService) {
this.modelService.mapTo(this);
}
}
stackblitz: https://stackblitz.com/edit/angular-ivy-hkwj81?file=src/app/hi.component.ts
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/399260.html
