Angular/TypeScript: _v.context.$implicit.getcolor 不是函数

Angular/TypeScript: _v.context.$implicit.getcolor is not a function

我正在做一个 Angular 7 项目,运行 遇到了一个我没想到的奇怪情况。 Angular 和 TypeScript 有点新.. 我想在我的 html 中使用 4 个不同的 css classes 之一。 class 名称是根据 location.ts 文件中的计算确定的。不是什么复杂的东西,但仍然令人沮丧,为什么我不能像我认为的那样使用 angular/typescript。做这样的事情的正确方法是什么?

location.ts 它是我尝试从 html.

获取的 getcolor() 函数
export class Location {
  location: string;
  name: string;
  current: number;
  max: number;
  isActive: boolean = false;
  color: string;

  getcolor() {
    let fraction = this.current / this.max;
    switch (true) {
      case (fraction < 0.25): { return "empty"; }
      case (fraction < 0.5): { return "half-empty"; }
      case (fraction < 0.75): { return "half-full"; }
      case (fraction < 1): { return "full"; }
      default: { return ""; }
    }
  }
}

location.service.ts

  getLocationList(): Observable<Location[]> {
    let list = this.http.get<Location[]>(this.url + "locations/");
    return list;
  };

map.component.ts

constructor(private locationService: LocationService) { }

  public locationList: Location[];

  ngOnInit() {
    this.locationService.getLocationList().subscribe(e => this.locationList = e);
  }

map.component.html 每张卡片都应该具有四种不同的 css 风格之一。可能不是这样做的方法,但现在我们只需要一些工作。对更正确方法的任何建议表示赞赏 :) 我只是尝试调用 Location class 上的方法以获取要使用的 css 样式的名称。

<div *ngFor="let loc of locationList" class="card {{loc.getcolor()}}">
        <span><strong>{{loc.location}}</strong> - {{loc.name}}</span>        
        <div>
          Storage: {{loc.current}}/{{loc.max}} tons
        </div>
        <div>
          Remaining: {{loc.max - loc.current}} tons
        </div>
      </div>

您正在尝试在获取订阅答案之前调用函数 getColor。你应该做两件事:

  • 确保 locationList 是 Location 类型的数组(您没有显示属性初始化,例如 private locationList: Array<Location>
  • 检查 loc 是否未定义

最后但同样重要的是,您应该使用 NgClass 来绑定 class !

好的,所以我找到了解决方案! :)

location.service.ts

    export class LocationService {
      constructor(private http: HttpClient) { }
      public url = "/api/location/"
      getLocationList(): Observable<Location[]> {
        return this.http.get<Location[]>(this.url + "locations/").pipe(map(x => x.map(y => Location.fromJSON(y)))); 
      };
    }

location.ts 将此静态函数添加到 location.ts

static fromJSON(data: any) {
    return Object.assign(new this, data);
  }

map.component.ts 这和以前一样。

  constructor(private locationService: LocationService) { }

  locationList: Location[];
  selectedLocation: Location;

  ngOnInit() {
    this.locationService.getLocationList().subscribe(e => this.locationList = e);
  }

map.component.html 现在我可以把颜色弄出来了:)

<div *ngFor="let loc of locationList" class="card {{loc.getcolor()}}">
        <span><strong>{{loc.location}}</strong> - {{loc.name}}</span>        
        <div>
          Storage: {{loc.current}}/{{loc.max}} tons
        </div>
        <div>
          Remaining: {{loc.max - loc.current}} tons
        </div>
      </div>

您可以尝试将 getToal 绑定到此组件,因为您只能调用其中声明的模板中的函数