Totally lost my mind. I'm confused. My goal is to get reply from my backend server. Here how it works: GET http://localhost:12345/createUser.php?name=John&age=40 returns me this json:
{
"id":"91",
"name":"John",
"age":40,
"birthday":"null"
}
I'd like to send this get request via angular and show reply to the page. I ONLY need id and name. So, I create model:
export class User {
id:string;
name:string;
}
And trying to get reply. Here's my two tryes: 1. Just code inside 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");
}
}
and create button and text-div in app.component.html to display it:
<button (click)="createUser()">Create test user!</button>
<div ><h2>{{user.id}} {{user.name}} </h2></div>
Aaand.. no result here. But, if I code html like "{{user | json}}", then I get some reply, but it's just request info like this:
{ "_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);
}
}
and app.component:
user:User;
ngOnInit()
{
return this.dataService.createUser().subscribe(data=>this.user=data);
}
No success. But user is created at my server on both ways. I see that I don't understand some basics, but can't find any good explanation on web. Could you please help me?
First of make sure your api/service is working as expected, i mean its actually returning the required response as you have stated above. Also here is a sample code i have created
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>
You see this piece of code working here Stackblitz . Hope this helps :). Let me know if you still face issues.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.