簡體   English   中英

angular服務中如何調用web api

[英]How to call web api in angular service

我是 angular 的新手。有人可以幫助我知道如何在 angular 代碼中調用我的 api 嗎?

我的我們 API 是 -

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

在環形中,我想像下面這樣打電話 -

客戶.component.ts -

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

客戶服務代碼 -

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

客戶.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);
    }
    );
}

我認為最好的實現是:

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

首先在 app.module.ts 文件中導入 HttpClientModule 並設置導入:

import { HttpClientModule } from '@angular/common/http';

imports: [
BrowserModule,
HttpClientModule,
],

現在創建一個服務並將此代碼添加到您的服務文件中

import { HttpClient } from '@angular/common/http';

export class EmployeeService {
private url='Enter your api url';
constructor(private httpClient: HttpClient) { }
getPost(){
 return this.httpClient.get(this.url);
 }
}

現在在 app.component.ts 文件中添加這段代碼

import {ApiService} from './services/api.service';

export class AppComponent {
posts:any;
constructor(private post:EmployeeService) {}

ngOnInit(){
this.post.getPost().subscribe(response =>{
this.posts=response;
console.log(this.posts);
 })
}
}

現在在 app.component.html 文件中

 <tr *ngFor="let post of posts">
<td>{{post.name}}</td>
</tr>

現在完成,保存並運行您的應用程序

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM