上下文。不是函数打字稿错误

时间:2019-06-26 19:28:05

标签: angular typescript

我有以下课程

import { ClassAsset } from './class-asset';

export class Class {
    ClassId:string;
    ClassName:string;
    Assets:ClassAsset[];

    GetAssetsString():string{
        var str:string;
        this.Assets.forEach(a=>{
            str+=a.AssetName;
        });

        return str;
    }

具有以下角度视图代码

<tr *ngFor="let cls of classList">
        <td>{{cls.className}}</td>
        <td>{{cls.GetAssetsString()}}</td>
      </tr>

我的组件看起来像这样

export class ClassesComponent implements OnInit {
  private _client:HttpClient;
  public classList:Class[]=[];

  constructor(client:HttpClient,private route:Router,private datasource:DataService) {
    this._client=client;
   }

  ngOnInit() {
    this.getClasses();
  }

  getClasses()
  {
    this.datasource.getClassList().subscribe((resp:Class[])=>{
      console.log(resp);
      this.classList=resp;}
      );
  }
}

但是我得到了错误

  

TypeError:_v.context。$ implicit.GetAssetsString不是函数

我在做什么错? (我仍然习惯于打字稿...)

1 个答案:

答案 0 :(得分:0)

因为您正在广播从服务器收到的响应到您的 Class 对象中。而且最有可能是具有数据但没有功能的对象。这就是 GetAssetsString 函数在您的代码中不可用的原因。

话虽如此,您可以像这样在 Class 对象中创建构造函数

export class Class {
    ClassId:string;
    ClassName:string;
    Assets:ClassAsset[];

    constructor(obj?:any){
      this.ClassId= obj && obj.ClassId || '';
      this.ClassName= obj && obj.ClassName || '';
      this.Assets = obj && obj.Assets || [];
    }

    GetAssetsString():string{
        var str:string;
        this.Assets.forEach(a=>{
            str+=a.AssetName;
        });

        return str;
    }
}

您的getClasses方法将像这样修改

          getClasses()
          {
            this.datasource.getClassList().pipe(map(response =>
            response.json())).subscribe(x=>{
              this.classList= x.map(x1=>new Class(x1));
              });
          }

谢谢。