如何从我的 c# web api 中填写 angular 7 中的 material 下拉列表?

How do I fill a material dropdownlist in angular 7 from my c# web api?

我是 angular 的新手,正在尝试了解如何通过 C# .NET Web API 在 angular 中绑定下拉列表。这是我在我的应用程序中所做的:

MVC Web API模型

[Table("tblShirt")]
public class Shirt
{
    [Key]
    public int ShirtID { get; set; }
    public string ShirtName { get; set; }
    public string ShirtCode { get; set; }
    public bool IsActive { get; set; }
}

Angular 消费的控制器方法

[HttpGet]
[AllowAnonymous]
public IEnumerable<Shirt> GetShirtCodes()
{
    var result = (from r in db.Shirts where r.IsActive == true orderby r.ShirtCode select r).ToList();
    return (result);
}

component.html

<mat-form-field style="width:inherit;">
  <mat-label>Shirt Code</mat-label>
    <mat-select>
      <mat-option *ngFor="let shirt of shirts" [value]="shirts.value">
        {{shirts.viewValue}}
      </mat-option>
     </mat-select>
 </mat-form-field>

除此之外,我还在自己的模型中镜像了模型 model.ts。这就是我被困的地方。我读过的所有教程都从这里开始。我在 component.ts

中尝试了以下方法
import { Component, OnInit } from '@angular/core';
import { ReprintService } from 'src/app/shared/reprint.service';
import { FormBuilder, Validators } from '@angular/forms';
import { Observable } from 'rxjs';
import { Reprint } from 'src/app/shared/reprint.model';
import { NotificationService } from 'src/app/shared/notification.service';
import { MatDialog } from '@angular/material';

public GetShirtCodes = (): Observable<any> =>  
{  
    return this._http.get(this.actionUrl)  
        pipe.(map((response: Response) => <any>response.json())); //shows error on response
}

但我认为这是一个过时的解决方案。

作为新手不要使用 Observables,试试这个

this._someService.SearchSomeData(this._someId).
subscribe(x =>
{
    this.someInfo =x;
});        

您的 someService 方法可能如下所示:

@Injectable()
export class CoursesService {

constructor(private _http: HttpClient) { }

SearchSomeData(id, ){
    return this._http.get("/api/Search/GetSomeData/"+id );
}

你的 Component.html 必须这样修正:

<mat-form-field style="width:inherit;">
  <mat-label>Shirt Code</mat-label>
    <mat-select>
      <mat-option *ngFor="let shirt of shirts" [value]="shirt.ShirtID">
        {{shirt.ShirtName}}
      </mat-option>
     </mat-select>
 </mat-form-field>

必须在您的模型中设置服务结果:

一般得到:

  public Get<T>(endPoint: string, options?: IRequestOptions): Observable<T> {
    return this.http.get<T>(this.api + endPoint, options);
  }

不太一般的人在服务上接到电话:

  getAll(endPoint: string): Observable<any> {
    return this.httpClient
      .Get(endPoint)
      .pipe(map(response => response));
  }

终于在您的组件中:

ngOnInit() {
this.service.getAll(endPoint).subscribe(res => {this.shirts = res});
}