Я вытаскиваю большой объект с моего сервера, используя услугу Angular 2 при запуске веб-сайта. Данные мне нужно тянуть выглядит так:Angular 2 Http Service Injectable
{
Edu: [...],
Exp: [...],
Links: [...],
Portfolio: [...],
Skills: [...]
}
И я настроить службу таким образом:
AllDataService:
import { Injectable, OnInit } from "@angular/core";
import { Http, Response } from "@angular/http";
import { Observable } from "rxjs/Rx";
@Injectable()
export class AllDataService {
private allDataUrl = ".../allData";
private loading: boolean;
private Edu: Array<any>;
private Exp: Array<any>;
private Links: Array<any>;
private Portfolio: Array<any>;
private Skills: Array<any>;
constructor(private http: Http) {
this.loading = true;
this.Edu = [];
this.Exp = [];
this.Links = [];
this.Portfolio = [];
this.Skills = [];
}
ngOnInit() {
this.getAllData();
}
// Get data from api, aka "Set" methods
getAllData() {
return this.http.get(this.allDataUrl)
.subscribe(
data => {
this.Edu = data.Edu;
this.Exp = data.Exp;
this.Links = data.Links;
this.Portfolio = data.Portfolio;
this.Skills = data.Skills;
this.loading = false;
},
err => console.error(err)
);
}
// “Get” methods
getLoading() { return this.loading; }
getEdu() { return this.Edu; }
getExp() { return this.Exp; }
getLinks() { return this.Links; }
getPortfolio() { return this.Portfolio; }
getSkills() { return this.Skills; }
}
И в моем компоненте я впрыснуть услугу так, чтобы Я могу получить данные:
HomeIcons:
import { Component } from "@angular/core";
import { AllDataService } from "../allDataService";
@Component({
selector: "home-icons",
template: `
<div class="home-icons-wrapper">
<ul class="home-icons-ul no-select">
<li class="home-icons-li"
*ngFor="let link of links" >
<a href={{link.url}} target="_blank">
<span class="home-icons-icon {{link.icon}}"></span>
</a>
</li>
</ul>
</div>
`,
providers: [AllDataService]
})
export class HomeIcons {
public links;
constructor(private http: Http, private allDataService: AllDataService) {
this.links = allDataService.getLinks();
}
}
Однако в AllDataService сообщение об ошибке сообщает мне, что свойства (Exp, Edu, Skills ...) не существуют в Response. Как правильно настроить службу http, чтобы я мог получить данные, которые я хочу при запуске, и убедиться, что все компоненты получают данные? Благодаря
Не могли бы вы опубликовать ваши данные в формате JSON ? И вы реализовали метод ToJson? –
Можете ли вы показать код метода ToJson. Является ли ошибка временем компиляции? –
Мне было плохо включать ToJson(), это просто попытка, проигнорировать его, я уже вынул его из своего кода. – thousight