-1

我有一个通过 id 获取帖子的示例 api,在我的组件中,我有一个对象配置要发送到子组件中,这个配置对象包含要在子组件中执行的 api。当 api 在子组件中执行时,我在 httpClient 中收到错误

无法读取未定义的属性“获取”

堆栈闪电战

@Injectable()
export class ApplicationAPI {
  constructor(private http: HttpClient) {}

  public getPost(id: string): Observable<any> {
    return this.http.get<any>("https://jsonplaceholder.typicode.com/posts/" + id);
  }
}

父组件

  config = {
    columns: [
      {
        defaultValue: { dependFromAPI: this.api.getPost }
      }
    ]
  };

子组件

 ngOnChanges(changes: SimpleChanges) {
    if (changes["config"] && changes["config"].currentValue) {
      changes["config"].currentValue.columns[0].defaultValue.dependFromAPI("43").subscribe(item => console.log(item))
    }
  }
4

1 回答 1

1

您需要将函数绑定到对象属性。一种方法是使用箭头函数表示法

config = {
  columns: [
    {
      defaultValue: { dependFromAPI: (id) => this.api.getPost(id) }
    }
  ]
};
于 2020-07-08T11:22:38.663 回答