簡體   English   中英

從http獲取結果Angular7獲取請求

[英]Get result from http get request Angular7

完全失去了理智。 我糊塗了。 我的目標是從后端服務器獲得答復。 它是這樣工作的:GET http:// localhost:12345 / createUser.php?name = John&age = 40向我返回此json:

{
    "id":"91",
    "name":"John",
    "age":40,
    "birthday":"null"
}

我想通過angular發送此get請求並顯示對頁面的回復。 我只需要ID和名稱。 因此,我創建模型:

export class User {
    id:string;
    name:string;
}

並試圖得到答復。 這是我的兩個嘗試:1.只需在app.component.ts中進行編碼:

export class AppComponent implements onInit{ 
  user:User; 

  constructor(private http:HttpClient) { }

  createUser(){
    this.user = this.http.get("http://localhost:12345/createUser.php?name=test&age=20"); 
  }
}

並在app.component.html中創建按鈕和text-div以顯示它:

<button (click)="createUser()">Create test user!</button> 
<div ><h2>{{user.id}} {{user.name}} </h2></div>

Aaand ..沒有結果。 但是,如果我編寫類似“ {{user | json}}”的html,那么我會得到一些回復,但這只是請求信息,如下所示:

{ "_isScalar": false, "source": { "_isScalar": false, "source": { "_isScalar": false, "source": { "_isScalar": true, "value": { "url": "http://localhost:12345/createUser.php?name=John&age=40", "body": null, "reportProgress": false, "withCredentials": false, "responseType": "json", "method": "GET", "headers": { "normalizedNames": {}, "lazyUpdate": null, "headers": {} }, "params": { "updates": null, "cloneFrom": null, "encoder": {}, "map": null }, "urlWithParams": "http://localhost:12345/createUser.php?name=John&age=40" } }, "operator": { "concurrent": 1 } }, "operator": {} }, "operator": {} } 
  1. 第二種嘗試是創建數據服務。 這是我的服務:
export class DataService {

  apiUrl="http://localhost:12345/createUser.php?name=John&age=40";
  constructor(private http:HttpClient) { }

  public createUser()
  {
    return this.http.get<User>(this.apiUrl);
  }
}

和app.component:

user:User;
ngOnInit()
  {
    return this.dataService.createUser().subscribe(data=>this.user=data); 
  }

沒有成功 但是用戶是通過兩種方式在我的服務器上創建的。 我發現我不了解一些基本知識,但是在網絡上找不到任何好的解釋。 請你幫助我好嗎?

首先,請確保您的api /服務能夠按預期工作,我的意思是它實際上返回了您如上所述的所需響應。 這也是我創建的示例代碼

  constructor(private httpClient: HttpClient){}
  name = 'Angular';
  data: Data;
  getData(){
    return this.httpClient.get<Data>(`https://swapi.co/api/people/1/`);
  }
  ngOnInit(){
    this.getData().subscribe((res: Data)=>{this.data = res;})
  }

export interface Data{
  name: string;
  height: string;
}

<p>
  Name : {{data.name}} <br>
  Height: {{data.height}}
</p>

您會在Stackblitz上看到這段代碼。 希望這可以幫助 :)。 讓我知道您是否仍然遇到問題。

暫無
暫無

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

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