Exemplo De Resposta Angular 2 Http Get

Qual é a forma correcta de obter os dados do json a partir de um HTTP get in Angular 2. Estou trabalhando em testar alguns dados locais com um ponto final ridicularizado, e posso ver o resultado no http.get() mas não posso atribuí-lo localmente ou há algum problema de tempo. Aqui está o meu simples serviço:

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';  // we need to import this now

    @Injectable()
    export class MyHttpService {
    constructor(private _http:Http) {}

    getDataObservable(url:string) {
        return this._http.get(url)
            .map(data => {
                data.json();
                console.log("I CAN SEE DATA HERE: ", data.json());
        });
    }
}
E eis como estou a tentar atribuir os dados:
import {Component, ViewChild} from "@angular/core";

import { MyHttpService } from '../../services/http.service';

@Component({
    selector: "app",
    template: require<any>("./app.component.html"),
    styles: [
        require<any>("./app.component.less")
    ],
    providers: []
})
export class AppComponent implements OnInit, AfterViewInit {
    private dataUrl = 'http://localhost:3000/testData';  // URL to web api
    testResponse: any;

    constructor(private myHttp: MyHttpService) {
    }

    ngOnInit() {
        this.myHttp.getDataObservable(this.dataUrl).subscribe(
            data => this.testResponse = data
        );
        console.log("I CANT SEE DATA HERE: ", this.testResponse);
    }
}
Posso ver os dados que quero na chamada "get", mas parece que Não tenho acesso a ele depois dessa chamada...por favor, diz-me o que estou a fazer. errado!

Author: Andrew Diamond, 2016-10-23

3 answers

Isso não devia funcionar assim. Quando os dados chegam, o callback passado para o observável é chamado. O código que precisa de aceder a estes dados tem de estar dentro do callback.
ngOnInit() {
    this.myHttp.getDataObservable(this.dataUrl).subscribe(
        data => {
          this.testResponse = data;
          console.log("I CANT SEE DATA HERE: ", this.testResponse);
        }
    );
}

Actualizar

getDataObservable(url:string) {
    return this._http.get(url)
        .map(data => {
            data.json();
            // the console.log(...) line prevents your code from working 
            // either remove it or add the line below (return ...)
            console.log("I CAN SEE DATA HERE: ", data.json());
            return data.json();
    });
}
 16
Author: Günter Zöchbauer, 2016-10-23 17:40:57

Porque a chamada http é async. Você precisa fazer tarefas na função subscrever. Tenta assim:

this.myHttp.getDataObservable(this.dataUrl).subscribe(
            data => {
                      this.testResponse = data ;
                      console.log("I SEE DATA HERE: ", this.testResponse);
                     }
        );
 5
Author: Sefa, 2016-10-23 17:18:12

Aqui está uma amostra fácil de usar que lhe permite usar promessas.

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Config } from '../Config';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';

@Injectable()
export class Request {

    constructor(public http: Http)
    {

    }

    get(url): Promise<any>
    {
        return this.http.get(Config.baseUrl + url).map(response => {
            return response.json() || {success: false, message: "No response from server"};
        }).catch((error: Response | any) => {
            return Observable.throw(error.json());
        }).toPromise();
    }

    post(url, data): Promise<any>
    {
        return this.http.post(Config.baseUrl + url, data).map(response => {
            return response.json() || {success: false, message: "No response from server"};
        }).catch((error: Response | any) => {
            return Observable.throw(error.json());
        }).toPromise();
    }
}
 1
Author: Azarus, 2018-01-19 02:13:06