【问题标题】:How to call web api in angular service如何在角度服务中调用 web api
【发布时间】:2020-11-10 07:46:17
【问题描述】:

我是 Angular 的新手。有人可以帮我知道如何用角码调用我的 api 吗?

我的 We API 是 -

[HttpGet,Route("api/customer/getCustomer/{name}")]
public async Task<IHttpActionResult> getCustomer([FromUri] string name) {
...}

并且在 anular 中,我想像下面这样调用 -

customer.component.ts -

name = "test";
getCustomer(){
this.custService.getCustomer(this.name).subscribe((data) => {
this.cust = JSON.parse(data.toString());
});
}

custService 代码 -

getCustomer(name){
 return this.http.get('https://localhost:44400/api/customer/getCustomer/', +name)
}

【问题讨论】:

  • get 调用中的逗号需要删除:this.http.get('https://localhost:44400/api/customer/getCustomer/' + name)。此外,如果后端已经在发送有效 JSON 中的对象,则不需要 JSON.parsetoString。你可以直接this.cust = data.

标签: c# angular asp.net-web-api


【解决方案1】:

customer.component.ts

export class CustomerComponent implements OnInit {
name: string;
cust: any;
constructor(private custService: CustService){
}
ngOnInit(){
    this.name = "test";
    this.getCustomer();
}

getCustomer(){
    this.custService.getCustomer(this.name).subscribe((data) => {
    this.cust = data;
    },error => {
        console.log(error);
    }
    );
}

【讨论】:

    【解决方案2】:

    我认为最好的实现是:

    1. 为您的服务器端 URL 定义一个配置文件:
      const  serviceBaseUrl: 'https://localhost:44400/api',
    
    
    
     public getCustomer(name:string): Observable<Customer> {
        return this.httpClient.get<any>(`${serviceBaseUrl}/customer/getCustomer/`+name);
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-06
      • 2012-10-08
      • 2021-03-13
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多