为什么数据不能从observable中获取?

问题描述 投票:0回答:1

我有一个服务,它向服务器发出GET请求来获取值,当我要把值存储在组件中的一个变量中时,就会出现问题。

abc.service.ts

public data: Category[] = [];
getPosts():Observable<Category[]> {
    return this.http.get<Category[]>(this.url + '/getAllExamCategory');
}

def.component.ts

ELEMENT_DATA: Category[];
dataSource: any;
columnsToDisplay = ['id', 'examCategoryName', 'isActive', 'Action'];

constructor(private adminCategory: AdminCategoryService) { }

ngOnInit() {
    this.adminCategory.getPosts().subscribe((reponse: Category[]) => {
      if(!reponse) {
        return;
      }
      this.ELEMENT_DATA = reponse;
      this.dataSource = new MatTableDataSource<Category>(this.ELEMENT_DATA);
      this.dataSource.paginator = this.paginator;
    }, error => {
      console.log(error);
    });
  }

我不明白是哪里出了问题。当我在控制台记录时 ELEMENT_DATA 检查它的长度,它显示的是 undefined.

angular typescript http angular9
1个回答
0
投票

试试这个...

getPosts():Observable<Category[]> {
    return this.http.get<Category[]>(this.url + '/getAllExamCategory')
       .pipe(map((reponse: any) => {
           console.log(reponse);
           return reponse;
        })
    );
}
© www.soinside.com 2019 - 2024. All rights reserved.