首页 > 解决方案 > 页面上的角度吸气剂

问题描述

我想要这样的 C# 代码:

public class MyClass
{
    public int SomeInt {get;set;}
    public string StatusDescription 
    {
        if (SomeInt == 0}
        {
             return "Zero";
        }
        else 
        {
            return "Not Zero";
        }
    }
}

所以在我的页面上,我可以做这样的事情:

<div class="col" *ngFor="let someClass of allMyClasses">
<mat-card class="example-card mt-2">
    <mat-card-header>
    <mat-card-content>
        <label>{{someClass.statusDescription}}</label>
    </mat-card-content>
</mat-card>
</div>

我解决这个问题的尝试是:

export class myClass{
    someInt: number;
    get statusDescription(): string
    {
        return "Status";
    }
}

我的打字稿

import { Component, OnInit } from '@angular/core';
import { myClass } from '../models/myClass';

@Component({
  selector: 'app-landing',
  templateUrl: './myClass.component.html',
  styleUrls: ['./myClass.component.css']
})
export class MyClassComponent implements OnInit {

  allMyClasses: Array<myClass> = new Array<myClass>();
  constructor(private myClassService: MyClassService  ) 
  { 
  }

  ngOnInit() {
  }


  fetchMyClasses()
  {
    this.myClassService.getMyClasses().then(
    (results) => this.allMyClasses= results
    );
  }

}  

我的类服务。我确信这件作品有效,因为我可以看到从这里提取的数据,以及页面/模板上显示的其他属性。

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { myClass } from '../models/myClass';

@Injectable({
  providedIn: 'root'
})
export class MyClassService {

  baseUrl: string = "https://localhost:44313/api/myClass/";
  constructor(private httpClient: HttpClient) { }

  getMyClasses()
  {
    const url = `${this.baseUrl}getMyClasses`;
    const result = this.httpClient.get<Array<myClass>>(url, {}).toPromise();
    return result;
  }

}

但是,当我的页面呈现时,它不显示“状态”,控制台中也没有错误或警告。我究竟做错了什么?

标签: angulartypescript

解决方案


the problem is how you create the elements of allMyClasses. If you write, e.g.

allMyClasses:myClass[]=[new myClass(),new myClass()];

Works perfectly. I supouse you has a problem when create the list

NOTE you can use some like

   cont class=Object.assign(new myClass(),{someInt:3})

   //or, e.g.
   this.allMyClasses.push(Object.assign(new myClass(),{someInt:3}))

To create an object myClass with both "properties":, someInt and statusDescription

Update so, if you has a list

this.myClassService.getMyClasses().then(
    (results) => this.allMyClasses= results.map(x=>Object.assign(new myClass(),x))
    );

NOTE: Why is the reason to convert to promise? For me has no sense

See stackblitz


推荐阅读