如何正确地从Angular 2中的http.get中提取JSON数据? [英] How to extract JSON data from http.get in Angular 2 properly?

查看:132
本文介绍了如何正确地从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:

我在这里有项目:推荐答案

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

This is an async operation, so when you try to console.log the result it's undefined, as it is being run before the other console.log inside the subscription.

.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请求的最佳方法.因此,只需在服务中使用map并将可观察到的内容返回给组件,请记住添加return语句:

I would make some changes to your code... I would suggest you take care of the subscription in the component instead, this would be the best way to handle http-requests. So just map in the service and return the observable to the component, remember to add return statement :

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

在您的组件中,我建议您将服务呼叫移至OnInit中.在这里您还可以注意到,根据代码中的注释,无法在订阅之外立即访问这些值.因此,如果您想以某种方式处理数据,则需要考虑到这一点:)

In your component I would suggest you move your service call in OnInit instead. Here you can also notice that the values aren't instantly accessible outside the subscription as per comments in code. So if you want to manipulate your data somehow, you need to take that into consideration :)

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

这是异步操作,因此请准备使用ngIf

AS this is an async operation, so be prepared to use either ngIf or the safe navigation operator in your view, since view is rendered before data has been retrieved.

因此可以将您的代码包装在ngIf中:

So either wrap your code inside ngIf:

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

{{gullkorn?.someProperty}}

这篇关于如何正确地从Angular 2中的http.get中提取JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆