簡體   English   中英

為什么我不能在這個 Angular 9 應用程序中將變量從組件傳遞到服務?

[英]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.idundefined

我究竟做錯了什么?

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'; [])) ); } }

  • 我們直接從方法getItemInfo而不是在服務上創建引用id參數。 在服務上定義它實際上是可以的,但它很容易受到攻擊,因為它是公開的,並且每次你通過服務設置它時,它都會保留該值,除非你打算這樣做以引用另一個服務。

在您的模板中,刪除 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) }) }
-您不必指定 stopProgation,因為您沒有進行任何冒泡事件行為或重定向

注意:替換為您的服務的實際名稱

我希望我解釋一下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM