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

Angular 如何通过HttpClient调用服务来初始化组件数据,angular,rxjs,angular7,Angular,Rxjs,Angular7,我看到很多类似的帖子,但没有一个对我有效。所以请不要让我去读其他的帖子,因为我在这里发帖之前就这么做了。 我试图通过调用服务来初始化组件属性。以下是组件代码: export class MyComponent implements OnInit { myData: number[]; constructor(@Inject(MyService) private myService: MyService) { } ngOnInit() { this.myService.getMyD

我看到很多类似的帖子,但没有一个对我有效。所以请不要让我去读其他的帖子,因为我在这里发帖之前就这么做了。 我试图通过调用服务来初始化组件属性。以下是组件代码:

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));
}
因此,为了恢复,组件通过调用rest端点订阅服务返回的可观察对象。rest端点按预期工作,调用correctle并返回正确的响应。 这个异常可能和异步操作类型有关,但我不知道该如何处理它。 此外,我不需要操作是异步的,但是,令人惊讶的是,我没有找到任何方法在angular中执行同步rest调用。 有人能再解释一下吗?非常感谢。
Nicolas

可能您正在使用
getMyData()
中的变量
this.numbers
作为可观察变量,因此您的
未定义的错误

你可能想做的事情是这样的:

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

请注意,异常是在组件的ngOnInit()方法中引发的,而不是在服务的ngOnInit()方法中引发的。我不确定这是否显而易见。
ngOnInit() {
    this.numbers =  this.http.post<MyDataResponse> (this.url, new MyDataRequest(100));
}