javascript - 从 http get 请求 Angular7 获取结果

标签 javascript http httpclient angular7

完全失去了理智。我很困惑。我的目标是从我的后端服务器获得回复。它是这样工作的:GET http://localhost:12345/createUser.php?name=John&age=40返回我这个 json:

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

我想通过 Angular 发送此获取请求并显示对页面的回复。我只需要 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.. 这里没有结果。但是,如果我将 html 编码为“{{user | json}}”,那么我会得到一些回复,但它只是请求这样的信息:

{ "_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);
  }
}

和应用程序组件:

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 . 希望这可以帮助 :)。如果您仍然遇到问题,请告诉我。

关于javascript - 从 http get 请求 Angular7 获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55410015/

相关文章:

javascript - jQuery 属性命令

javascript - 将现有 API 的回调包装在 promise 中以避免 "callback hell"有好处吗?

javascript - 来自属性的变量只显示第一个词

security - 在 cookie 中存储 API 的用户名和密码?

c - 你知道任何用 C 编写的开源 Http 客户端,它可以在 *nix 和 Windows 上运行吗?

javascript - RHS 分配优于 LHS 操作

php - 使用 XML 标记属性作为 PHP 变量并在 HTTP 请求中使用它

web-services - 如何在 Mongoose 网络服务器上保持链接有效

android - 有没有办法在 AsyncTask 中停止 HttpClient 的执行?

android - Android 上的 reCAPTCHA?