T
T
tupoi2017-03-17 22:40:57
JavaScript
tupoi, 2017-03-17 22:40:57

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
}

to represent the data, I create a user.ts file
export class User {
  name: string;
  age: number;
}

write logic in service
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')
  }
}

I call everything in the component
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>

As a result, on the page only "Username:" and everything, as if the values ​​did not come, can someone tell me what exactly I'm doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dasha Tsiklauri, 2017-03-18
@dasha_programmist

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 question

Ask a Question

731 491 924 answers to any question