我似乎无法使用 json 文件中的信息为 View 创建一个变量,但我已经很接近了。我可以回显 .subscribe()
链中的信息,但它不会将其设置为变量,它们只是未定义,我做错了什么?
我只想将 json 文件加载到组件 View 中的变量中。在 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 请求的最佳方式。因此,只需在服务中map
并将可观察到的结果返回给组件,记住添加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
}
因为这是一个异步操作,所以准备使用 ngIf
或 safe navigation operator 在您的 View 中,因为 View 是在检索数据之前呈现的。
因此,要么将代码包装在 ngIf
中:
<div *ngIf="gullkorn"></div>
或{{gullkorn?.someProperty}}
关于angular - 如何在 Angular 2 中正确从 http.get 中提取 JSON 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42173762/