Answer the question
In order to leave comments, you need to log in
How to make a get request in angular 2?
Good day, can someone tell me what exactly I'm doing wrong?
The goal is to send a Get request and output the received data to the page.
create json file in folder
{
"name": "Bob",
"age": 28
}
export class User {
name: string;
age: number;
}
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class HttpService {
constructor(private http: Http) { }
getData() {
return this.http.get('./user.json')
}
}
import { Component, OnInit } from '@angular/core';
import { Response } from '@angular/http';
import { HttpService } from './http.service';
import { User } from './user';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [HttpService]
})
export class AppComponent implements OnInit {
user: User;
constructor(private httpService: HttpService) { }
ngOnInit() {
this.httpService.getData()
.subscribe((data: Response) => this.user=data.json());
}
}
<div>
<p>Имя пользователя: {{user?.name}}</p>
<p>Возраст: {{user?.age}}</p>
</div>
Answer the question
In order to leave comments, you need to log in
check with the browser debugger whether the data on request comes to './user.json', it may be cached
for the future, it is better to write such calls so
that an unsubscribe is made immediately, otherwise hanging subscribers are formed.
or already inside the component
this.subscriptions.push(this....subscribe())
ngOnDestroy(){
this.subscriptions.forEach(i=>i.unsubscribe())
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question