如何正确地从Angular 2中的http.get中提取JSON数据? [英] How to extract JSON data from http.get in Angular 2 properly?
本文介绍了如何正确地从Angular 2中的http.get中提取JSON数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我似乎无法使用json文件中的信息为视图创建变量,但我是如此接近.我可以回显.subscribe()
链中的信息,但不会将其设置为变量,它们只是未定义,我在做什么错了?
I can't seem to manage to make a variable for the view with the info from a json file but I'm so close. I can echo out the information in the .subscribe()
-chain, but it won't set it to a variable, they just get undefined, what am I doing wrong?
我只想将json文件加载到组件视图中的变量中.在Angular 1中很容易.
I just want to load my json file into a variable in the component view. It was easy in 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() {
}
}
根据当前代码,这就是我得到的:
Based on current code this is what I get:
查看全文