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

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

我这里有项目:github.

推荐答案

这是一个异步操作,所以当你尝试 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,将observable返回给组件,记得添加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天全站免登陆