完全失去了理智。我很困惑。我的目标是从我的后端服务器获得回复。它是这样工作的: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": {} }
- 第二个尝试是创建数据服务。所以这是我的服务:
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/