[英]How do I fill a material dropdownlist in angular 7 from my c# web api?
I am new to angular and trying to figure out how to bind a dropdownlist in angular from C# .NET Web API. 这是我在我的应用程序中所做的:
MVC Web API Model
[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; }
}
Controller 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);
}
组件.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 中镜像了我的 model。 这就是我卡住的地方。 我从这里向南阅读了 go 的所有教程。 我在我的 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>
对于必须在 model 中设置服务结果:
一般得到:
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});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.