【发布时间】:2017-10-11 14:20:50
【问题描述】:
当我通过我的服务检索数据时,我的 Angular 2 脚本的标题出现错误,但页面组件仍在使用 {{ bedriften }} 显示信息,即使我收到错误。我不知道我做错了什么。当我调用 console.log(this.bedriften) 时,它是未定义的,但会显示在页面上。我不确定如何在页面显示给用户之前正确加载信息(我的意思是 this.bedriften 被填充)
我的服务:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
@Injectable()
export class HendingService {
alleHendingar: any;
data: any;
constructor(private http: Http) { }
bed: any;
hentHendingar() {
return this.http.get("http://ekstremedia.no/rapporter/allehendingar.json")
.map(res => res.json());
}
hentBedrift(bed) {
return this.http.get("http://localhost:81/vossapp/get/bedrift/"+bed)
.map(res => res.json());
}
}
我的页面,我得到错误:
import { Component, OnInit, AfterContentInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HendingService } from '../../hending-service.service';
@Component({
selector: 'app-bedriftside',
templateUrl: './bedriftside.component.html',
styleUrls: ['./bedriftside.component.scss'],
providers: [HendingService]
})
export class BedriftsideComponent implements OnInit {
id: number;
private sub: any;
bedriften: any;
constructor(private route: ActivatedRoute, private hs: HendingService) { }
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.id = params['id'];
});
this.hs.hentBedrift(this.id)
.subscribe(data => {
this.bedriften = data
});
console.log(this.bedriften); // undefined
}
}
【问题讨论】: