Javascript 使用angular从指令中的API调用更新组件数据

Javascript 使用angular从指令中的API调用更新组件数据,javascript,angular,typescript,Javascript,Angular,Typescript,我是个新手,遇到了一个问题。我已经创建了一个带有.net核心web api后端的简单angular应用程序,并且我在更新组件数据时遇到了问题,因为我使用了一个指令来处理鼠标点击 我希望在单击鼠标时,get请求返回数据并更新页面。我已经阅读了observer模式,正在使用“rxjs”实现 这对于初始页面加载很好,但是当我单击时,我希望它发送另一个请求并更新页面上的数据。任何帮助都将不胜感激 这是我正在测试的Html组件 <div class="container"> <div

我是个新手,遇到了一个问题。我已经创建了一个带有.net核心web api后端的简单angular应用程序,并且我在更新组件数据时遇到了问题,因为我使用了一个指令来处理鼠标点击

我希望在单击鼠标时,get请求返回数据并更新页面。我已经阅读了observer模式,正在使用“rxjs”实现

这对于初始页面加载很好,但是当我单击时,我希望它发送另一个请求并更新页面上的数据。任何帮助都将不胜感激

这是我正在测试的Html组件

<div class="container">
  <div class="testDiv" appApplyitemclick>
    <img src="######" />
  </div>
  <div class="ShowDiv" *ngFor="let stat of storedItem.statistics" >
    <p>{{stat.name}}</p>
  </div>
</div>
这是我的指示

import { Directive, HostListener} from '@angular/core';
import { ItemAPIService } from '../Services/item-api.service'
@Directive({
  selector: '[appApplyitemclick]'
})
export class ApplyitemclickDirective {

  constructor(private api: ItemAPIService) { }

  @HostListener("click", ["$event"])
  public onMouseClick(event: any): void {

     // I WANT TO TO CALL THE API AND UPDATE THE PAGE HERE 
     // this.ItemApi.GetItem()
    }
}
下面是我的简单web api服务

@Injectable({
  providedIn: 'root'
})
export class ItemAPIService {

  constructor(private http: HttpClient) { }

  GetItem() {
    return this.http.get("http://localhost:1262/api/Item/get");
  }
}

您只需将主机组件
ItemComponent
实例注入指令类
ApplyitemclickDirective
,并刷新
storedItem
字段中的数据:

export class ApplyitemclickDirective {

  constructor(private api: ItemAPIService, private host: ItemComponent) { }

  @HostListener("click", ["$event"])
  public onMouseClick(event: any): void {

    //call API and update the state of the host component
     this.api.GetItem().subscribe(data =>{
     this.host.storedItem = data;

    });
   }
}

我认为指令不是正确的道路。你可以点击一下


并将
onInit
逻辑移动到新的
updateData
函数中(并从
onInit
调用它)


如果您真的想使用指令,我仍然会使用事件处理程序——只需向指令添加一个输出即可。您可以让事件发出服务请求的对象结果。

谢谢,我下班回家后会试试。如果有效,我会将其标记为已回答=)嗨,Amardeph,我注入了这个,但仍然没有得到要更新的数据。我的指令是另一个组件上的属性,这有关系吗?在将两个组件合并为一个组件后,此解决方案解决了我的问题。非常感谢!
export class ApplyitemclickDirective {

  constructor(private api: ItemAPIService, private host: ItemComponent) { }

  @HostListener("click", ["$event"])
  public onMouseClick(event: any): void {

    //call API and update the state of the host component
     this.api.GetItem().subscribe(data =>{
     this.host.storedItem = data;

    });
   }
}
  <div class="testDiv" (click)="updateData()">
    <img src="######" />
  </div>