如何通过 HttpClient 调用服务来初始化组件数据



我看到了几十个类似的帖子,但没有一个解决方案对我有用。所以请不要通过让我阅读其他帖子来回答,因为我在这里发布之前就这样做了。我正在尝试通过调用服务来初始化组件属性。下面是组件代码:

export class MyComponent implements OnInit {
  myData: number[];
  constructor(@Inject(MyService) private myService: MyService) {
}
ngOnInit() {
  this.myService.getMyData().subscribe(data => this.myData = data);
}

服务代码如下:

@Injectable()
export class MyService implements OnInit {
  private numbers: Observable<number[]>;
  constructor(@Inject(HttpClient) private http: HttpClient) {}
  getMyData(): Observable<number[]> {
    return this.numbers;
  }
ngOnInit() {
 this.http.post<MyDataResponse> (this.url, new MyDataRequest(100))
   .subscribe(resp => this.numbers = 
   observableOf(resp.data));
}

在运行时,我得到以下异常:

ERROR TypeError: Cannot read property 'subscribe' of undefined
at .../MyComponent.ngOnInit (...)
at checkAndUpdateDirectiveInline (core.js:18620)
at checkAndUpdateNodeInline (core.js:19884)
at checkAndUpdateNode (core.js:19846)
at debugCheckAndUpdateNode (core.js:20480)
at debugCheckDirectivesFn (core.js:20440)
at Object.eval [as updateDirectives] (...)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:20432)
at checkAndUpdateView (core.js:19828)
at callViewAction (core.js:20069

因此,为了恢复,组件通过调用 rest 终结点来订阅服务返回的可观察量。其余端点按预期工作,并得到正确的调用并返回正确的响应。例外可能与操作的异步类型有关,但我不知道我应该如何处理。此外,我不需要操作是异步的,但是,尽管可能令人惊讶,但我没有找到任何方法来执行角度同步的休息调用。谁能对此多说几句话?提前非常感谢。尼古拉斯

可能是您在getMyData()中使用变量 this.numbers 在成为可观察对象之前,因此您的错误undefined .

你可能想做的是这样的:

ngOnInit() {
    this.numbers =  this.http.post<MyDataResponse> (this.url, new MyDataRequest(100));
}

最新更新