如何从 Angular 2 中的 http.get 中正确提取 JSON 数据?

How to extract JSON data from http.get in Angular 2 properly?

我似乎无法使用 json 文件中的信息为视图创建变量,但我已经很接近了。我可以回显 .subscribe()-链中的信息,但它不会将其设置为变量,它们只是未定义,我做错了什么?

我只想将 json 文件加载到组件视图中的变量中。 Angular 1.

很容易

我的服务:

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class GullkornService { 
result: any;

constructor(private http:Http) {
}

getGullkorn()  {

let result = this.result;
this.http.get('./gk/gullkorn.json')
.map(res => res.json())
.subscribe(
        val => this.result = val,
        err => console.error(err),
        () =>  console.log(this.result));  // this one echoes out what i want
        console.log(this.result); // but this one doesnt, so i cant return it 
      }
}

以及着陆组件:

import { Component, OnInit } from '@angular/core';
import {Router, RouterOutlet} from '@angular/router';
import { HttpModule, JsonpModule } from '@angular/http';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule }      from '@angular/core';
import { GullkornService } from '../../gullkorn-service.service';
import { FormsModule }   from '@angular/forms';
import {Observable} from 'rxjs/Observable';

import "gsap";
declare var ease, TimelineMax,TweenMax,Power4,Power1,Power2,Power3,Bounce, Elastic:any;

@Component({
  selector: 'gullkorn-visning',
  providers: [GullkornService],
  templateUrl: './landing.component.html',
  styleUrls: ['./landing.component.css']
})
export class LandingComponent implements OnInit {
  gullkorn: any;
  constructor(GullkornService: GullkornService) { 
        this.gullkorn = GullkornService.getGullkorn();
        console.log(this.gullkorn);
  }

  ngOnInit() {
  }

}

根据当前代码,这是我得到的:

我这里有项目:github

这是一个异步操作,因此当您尝试 console.log 结果时,它是未定义的,因为它 运行 在订阅内的另一个 console.log 之前。

.subscribe(
        val => this.result = val,
        err => console.error(err),
        () =>  console.log(this.result));  // is run sometimes later
        console.log(this.result); // is run first
      }

我会对您的代码进行一些更改...我建议您改用组件中的订阅,这将是处理 http-requests 的最佳方式。所以只是 map 在服务和 return observable 到组件,记得添加 return 语句:

getGullkorn() {
  return this.http.get('./gk/gullkorn.json')
    .map(res => res.json())
}

在您的组件中,我建议您将服务调用移至 OnInit。在这里您还可以注意到,根据代码中的注释,无法在订阅外部立即访问这些值。所以如果你想以某种方式操纵你的数据,你需要考虑到这一点:)

ngOnInit() {
  this.GullkornService.getGullkorn()
    .subscribe(data => {
     // is run sometimes later
     this.gullkorn = data
  });
  // is run first
}

因为这是一个异步操作,所以请准备好在您的视图中使用 ngIfsafe navigation operator,因为视图在数据之前呈现已检索。

所以要么将代码包装在 ngIf:

<div *ngIf="gullkorn"></div>

{{gullkorn?.someProperty}}

最好return从服务中观察到并在组件中订阅它:

服务:

@Injectable()
export class GullkornService {

  constructor(private http:Http) {
  }

  getGullkorn()  {
    // Return the observable here
    return this.http.get('./gk/gullkorn.json')
    .map(res => res.json());
  }

}

组件:

@Component({
  selector: 'gullkorn-visning',
  providers: [GullkornService],
  templateUrl: './landing.component.html',
  styleUrls: ['./landing.component.css']
})
export class LandingComponent implements OnInit {
  gullkorn: any;
  constructor(GullkornService: GullkornService) { 
      GullkornService.getGullkorn()
        .subscribe(
            val => this.gullkorn = val,
            err => console.error(err)
  }

  ngOnInit() {
  }

}