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);
    });
  }

我无法理解在哪里犯了错误。当我在控制台 logginfELEMENT_DATA中检查变量的长度时,它正在显示undefined

4

1 回答 1

0

尝试这个..

getPosts():Observable<Category[]> {
    return this.http.get<Category[]>(this.url + '/getAllExamCategory')
       .pipe(map((reponse: any) => {
           console.log(reponse);
           return reponse;
        })
    );
}
于 2020-06-08T09:46:04.193 回答