[英]How can I pass a variable from @Input to a service in an Angular2 component>
[英]Why can't I pass variable from component to service in this Angular 9 application?
我正在使用 Anular 9 和 Angular Material 開發一個小型應用程序。 我有一個項目列表,每個項目都有一個“編輯”按鈕:
<div class="item-name">{{node.item.name}}</div>
<button mat-icon-button color="primary" (click)="editItem($event, node.item.id)">Edit</button>
我正在嘗試獲取組件中的項目 ID 並將其傳遞給服務:
在我的組件中:
public id: string;
editItem(event, id): void {
event.stopPropagation();
console.log("Item id is: " + id);
this.id = id;
}
在我的服務中:
getItemInfo(): Observable<any[]> {
console.log(this.id);
if (typeof this.id !== 'undefined') {
return this._http.get<any[]>(this.baseUrl + this.id, httpOptions)
.pipe(
catchError(this.handleError('getItemInfo', []))
);
}
}
來自組件的行console.log("Item id is: " + id)
輸出預期結果 - 當前項目的 id。
然而,在服務中this.id
是undefined
。
我究竟做錯了什么?
id 沒有在服務中定義,你可以像這樣在 function 中傳遞它:
在組件中:
import { YourService } from './servicePath';
...
constructor(public service: YourService ) { }
editItem(event, id): void {
event.stopPropagation();
console.log("Item id is: " + id);
this.service.id = id;
}
然后在服務中聲明一個 id
id:string;
getItemInfo(): Observable<any[]> {
console.log(this.id);
if (typeof this.id !== 'undefined') {
return this._http.get<any[]>(this.baseUrl + this.id, httpOptions)
.pipe(
catchError(this.handleError('getItemInfo', []))
);
}
}
在您的服務中,屬性id未定義,因為您沒有從組件中設置/傳遞它。 上面的評論對於從您的組件中設置“id”的引用是正確的,但我建議您更改設置屬性id的方式。
解決辦法就是這樣傳id
getItemInfo(id): Observable < any[] > { // create parameter id console.log(id); // log the id for check if (typeof id.== 'undefined') { // update this.id to id return this._http.get < any[] > (this,baseUrl + id. httpOptions) // update this.id to id.pipe( catchError(this,handleError('getItemInfo'; [])) ); } }
在您的模板中,刪除 editItem 中的$event ,因為它沒有用,並且您沒有在代碼中使用事件 object
<button mat-icon-button color="primary" (click)="editItem(node.item.id)">Edit</button>
在您的組件中,更新以下代碼中的editItem方法
editItem(id): void { console.log("Item id is: " + id); // you can call your service here or to another method // sample usage <YourService>.getItemInfo(id).subscribe(result => { console.log(result) }) }
注意:替換為您的服務的實際名稱
我希望我解釋一下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.