我似乎无法使用 json 文件中的信息为视图创建一个变量,但我已经很接近了。我可以回显中的信息.subscribe()
-chain,但它不会将其设置为变量,它们只是未定义,我做错了什么?
我只想将 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 https://github.com/ekstremedia/eks-app-2017/blob/master/src/app/gullkorn-service.service.ts.