jsonファイルの情報でビューの変数を作成することはできませんが、私はとても近いです。 .subscribe()
-chainの情報をエコーアウトできますが、変数に設定されません。定義されません。何が間違っていますか?Angular 2のhttp.getからJSONデータを正しく抽出するにはどうすればよいですか?
jsonファイルをコンポーネントビューの変数にロードするだけです。これは、角度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。
ありがとうございました!これは最初の試みで働いた、私のためのそのような闘いだった。時間をすごく感謝します。コンポーネントをサブスクライブしてこの関数を呼び出すと、トリックがかかりました! –
あなたは大歓迎です!うん分かりました。非同期操作は最初は非常に混乱しています!私の答えでこれをもう少し詳しく説明しました。gページのナビゲーションに何らかの形でコンポーネント内のデータを操作する必要がある場合は、サブスクリプションでデータが利用できる場所に注意する必要があります。どこにいなくても、将来的には役立つと思っています。 :) – Alex