【问题标题】:Type 'Alias[]' has no properties in common with type 'Alias'类型“别名 []”与类型“别名”没有共同的属性
【发布时间】:2020-03-29 01:26:28
【问题描述】:

我收到一个错误:

类型“别名[]”与类型“别名”没有共同的属性

这是我的别名

  alias: Alias = {
    id: 0,
    domain_id: 0,
    source: '',
    destination: ''
  };

这是我的 Alias 模型

export interface Alias {
    id?: number;
    domain_id?: number;
    source?: string;
    destination?: string;
}

我在这里出错了 this.alias = res

  ngOnInit() {
    const params = this.activedRoute.snapshot.params.id;
    console.log('parms '+params);
    if (params.id) {
      this.aliasesService.getAlias(params.id).subscribe(
        res => {
          this.alias = res;
          this.edit = true;
        },
        err => console.error(err)
      );
    }
  }

还有我的服务

getAlias(id: string): Observable<Alias[]> {
    return this.http.get<Alias[]>(`${this.API_URI}/aliases/${id}`);
  }

我该如何解决这个问题?

【问题讨论】:

  • this.aliasesService.getAlias(params.id) 返回什么?
  • 您正试图在别名类型的属性中引用别名数组。要么将属性更改为数组,要么让后端发回一个别名
  • 别名必须是别名 [] 而不是别名
  • 请在your last question about this 上查看my comment。名字很重要。当您的意思是 aliases 时使用 alias 是您需要解决的问题。同样,我强烈建议您为observe 回调的参数使用一个有意义的名称,而不是res。确保它与所提供的内容相匹配(alias 用于一个别名,aliases 用于多个别名)。它将帮助您避免这些问题。
  • @NicholasK 它返回一个别名

标签: node.js angular typescript express


【解决方案1】:

改变这个:

getAlias(id: string): Observable<Alias[]> {
  return this.http.get<Alias[]>(`${this.API_URI}/aliases/${id}`);
}

到这里:

//I guess this api returns a single Alias
getAlias(id: string): Observable<Alias> {
  return this.http.get<Alias>(`${this.API_URI}/aliases/${id}`);
}

编辑:

顺便说一句,你可以像这样简化你的代码

发件人:

alias: Alias = {
  id: 0,
  domain_id: 0,
  source: '',
  destination: ''
};

收件人:

alias: Alias = {} as Alias; //it's the same thing

【讨论】:

  • 它可以工作,但现在“res”返回对象 Object 而不是数组。所以我不能显示它
  • @MarrZZ 告诉我你的 html 代码和 console.log 的“res”
猜你喜欢
  • 1970-01-01
  • 2023-01-05
  • 1970-01-01
  • 2017-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-17
相关资源
最近更新 更多