I
I
Ivan-P2016-05-26 15:07:50
Angular
Ivan-P, 2016-05-26 15:07:50

What is wrong with http request in angular2?

I did everything according to the instructions from angular.io
app.service.ts:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AppService {

  constructor (private http: Http) {}
  private dataUrl = 'http://jsonplaceholder.typicode.com/users';
  private extractData(res: Response) {
    let body = res.json();
    return body || {};
  }

  getData (): Observable<any> {
    return this.http.get(this.dataUrl)
      .map(this.extractData)
  }
}

app.component.ts:
import { Component, OnInit } from '@angular/core';
import { AppService } from './app.service';
import '../../public/css/styles.css';

@Component({
  selector: 'my-app',
  providers: [AppService],
  template: require('./app.component.html'),
  styles: [require('./app.component.css')],
})

export class AppComponent implements OnInit {

  private users:any;
  constructor(private appService: AppService) {}

  ngOnInit() {
    this.appService.getData().subscribe(res => this.users = res);
    console.log(this.users);
  }
}

I get undefined in the console

Answer the question

In order to leave comments, you need to log in

1 answer(s)
_
_ _, 2016-05-26
@Ivan-P

ngOnInit() {
    this.appService.getData().subscribe(res => {
       this.users = res;
       console.log(this.users); 
    });
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question