【问题标题】:Why don't work find method and how get data in Angular?为什么不工作查找方法以及如何在 Angular 中获取数据?
【发布时间】:2021-05-23 22:39:35
【问题描述】:

这是我的代码:

  ngOnInit() {
    this.route.paramMap.subscribe(params => {
      console.log(params.get('id')); // THIS IS WORKS
      this.currentOrganization = this.getOrganizationId(params.get('id'));
      console.log(this.currentOrganization); // THIS IS UNDEFINED
    } );  
  }

  getOrganizationId(id: string) {
    let organizations = this.orgService.getOrganizations(); // THIS IS WORKS
    return organizations.find(p => p.id == id);
  }

为什么未定义 this.currentOrganization?如何获取 params.get('id') 的组织信息?

【问题讨论】:

标签: angular typescript ionic-framework routes


【解决方案1】:

您可以尝试在运行.find 之前添加if(organizations),这样只有在organizations 中有值时它才会开始到.find。像这样

getOrganizationId(id: string) {
    let organizations = this.orgService.getOrganizations();
    if(organizations) {
        console.log(organizations.find(p => p.id == id));
        return organizations.find(p => p.id == id);
    }
}

如果你想尝试不同的方法,你可能想试试这个

ngOnInit() {
    this.getOrganization();
}

getOrganization() {
    const organizationId = this.route.snapshot.paramMap.get('id');
    if (organizationId) {
      this.orgService.getOrganizations()
         .subscribe(org => {
                      console.log(org.find(p => p.id == organizationId));
                      return org.find(p => p.id == organizationId);
                    });
}

虽然对我来说最好有一个特定的服务,它只返回带有 id 的 get,因为我们仍然从路由中获取它。获取数据列表后,加载速度会更快,而不必再次执行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2011-03-20
    • 2020-08-31
    相关资源
    最近更新 更多