完全失去理智了。我很困惑。我的目标是从后端服务器获得回复。下面是它的工作原理: GET http://localhost:12345/createUser.php?name=John&age=40返回给我这个json:
{
"id":"91",
"name":"John",
"age":40,
"birthday":"null"
}我想通过角发送这个get请求并显示对页面的回复。我只需要身份证和名字。所以,我创建了模型:
export class User {
id:string;
name:string;
}并试图得到回复。下面是我的两个tryes: 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中创建按钮和文本div来显示它:
<button (click)="createUser()">Create test user!</button>
<div ><h2>{{user.id}} {{user.name}} </h2></div>还有..。这里没有结果。但是,如果我将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);
}
}和app.component:
user:User;
ngOnInit()
{
return this.dataService.createUser().subscribe(data=>this.user=data);
}没有成功。但是用户是在我的服务器上以两种方式创建的。我看不懂一些基本知识,但在网上找不到任何好的解释。你能帮帮我吗?
发布于 2019-03-29 03:46:20
首先,确保您的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>您可以看到这段代码在这里工作,斯塔克布利茨。希望这有帮助:)。如果你还面临问题请告诉我。
https://stackoverflow.com/questions/55410015
复制相似问题