【问题标题】:AngularJS 2 a Promise resolve loses class identity upon fechingAngularJS 2 a Promise resolve 在获取时丢失了类标识
【发布时间】:2017-05-19 09:59:08
【问题描述】:

总结: 我应该获取一些具有类方法的 Org 对象。但是当我获取我的数据时,我看到的是 Object 实例,而不是 Org 实例。这是最好的结果吗?或者我可以说服我的程序给我 Org 对象吗?

详情: 我正在使用最新版本的 Angular 2。我的代码稍微修改了一些教程代码。这是我的 org.service.ts 的一部分:

getOrgs(): Promise<Org[]> {
  return this.http
    .get(this.orgUrl)
    .toPromise()
    .then(response => response.json().data as Org[])
    .catch(this.handleError);
}

getOrg(id: number): Promise<Org> {
  return this.getOrgs()
    .then((orgs: Org[]) : Org => orgs.find(org => org.id === id));
}

这是我的解析器的一部分:

resolve(route: ActivatedRouteSnapshot): Promise<Org>|boolean {
  let id = this.authService.user.orgId;

  return this.orgService.getOrg(id).then((org: Org) : Org|boolean => {

    if(org) { // <-- Breakpoint here
      return org;
    } else { 
      // If  the Org isn't available then the edit page isn't appropriate.
      this.router.navigate(['/provider/home']);
      return false;
    }

  });
}

我正在通过内存服务获取我的数据:

export class InMemoryDataService {

  createDb() {
    let org1 = new Org();
    org1.id = 12;
    org1.donor = true;
    org1.name = 'Great Actors Theater';
    let org2 = new Org();
    org2.id = 19;
    org2.donor = false;
    org2.name = 'Sunnyside Group Home';
    let org: Org[] = [];
    org.push(org1);
    org.push(org2);
[SNIP]

而我的 Org 类是这样的:

export class Org {
  id: number;
  donor: boolean;
  name: string = "";

  deepCopy(): Org { ... }

  equals(other: Org): boolean { ... }
}

当我在断点处查看数据时,我看到一个具有字段(id、捐助者、名称)但没有函数的对象。我在那里也没有看到 Org 的定义——如果我调用“org instanceof Org”,我会收到一个错误,即找不到 Org。而“typeof org”产生“object”。

我希望有 equals() 等作为 Org 类方法。但目前我只有 like Org 的 Javascript 对象,只能通过鸭子打字。我能从中得到更好的结果吗?

谢谢, 杰罗姆。

【问题讨论】:

    标签: angular typescript promise angular-promise


    【解决方案1】:

    从 JSON 构造 Org 实例。

    类似:

    .then(response => {
       // validate response
       return response.json().data.map(d => new Org(d))
    })
    

    然后在类声明中定义如何构造Org实例例如:

    export class Org {
      id: number;
      donor: boolean;
      name: string = "";
    
      constructor(data: any) {
         // validate data
         this.id = data.id;
         this.donor = data.donor;
         this.name = data.name;
      }
      ...
    }
    

    【讨论】:

    • 这对我有用。就我上面的示例而言, getOrgs().then() 更改为 .then(response => response.json().data.map((d: any) => new Org(d)) 作为 Org[] )。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2017-05-24
    • 2021-03-11
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 2017-10-20
    相关资源
    最近更新 更多