【问题标题】:Why data is not fetched from the observable?为什么没有从 observable 中获取数据?
【发布时间】:2020-06-08 09:20:01
【问题描述】:

我有一项服务向服务器发出 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

【问题讨论】:

  • 确保您的 HTTP GET 成功返回一个值,console.log(response); 会有所帮助。
  • 是的,我得到了正确的响应

标签: angular typescript http angular9


【解决方案1】:

试试这个..

getPosts():Observable<Category[]> {
    return this.http.get<Category[]>(this.url + '/getAllExamCategory')
       .pipe(map((reponse: any) => {
           console.log(reponse);
           return reponse;
        })
    );
}

【讨论】:

  • 不,仍然有同样的问题。我能够通过 Observables 获得响应,但组件的长度仍为 undefined
  • 确保拼写正确(“reponse”和“response”)。此外,只有长度未定义或“未定义长度”错误?
  • 其实问题解决了,是传入的JSON的问题
猜你喜欢
  • 2022-11-23
  • 1970-01-01
  • 2011-11-08
  • 1970-01-01
  • 1970-01-01
  • 2019-03-31
  • 2019-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多