我的http get调用服务
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import { IAppInfo } from './appInfo';
import { IProduct } from './product';
@Injectable()
export class AppInfoService {
private _appInfoUrl : string = "api/appInfo/appInfo.json";
//constructor
constructor (private _http : Http){}
getAppInfo() : Observable<IAppInfo[]> {
return this._http.get(this._appInfoUrl)
.map((response : Response) => <IAppInfo[]>response.json())
.do(data => console.log('Service'+JSON.stringify(data)))
.catch(this.handleError);
}
private handleError(error : Response){
console.error(error);
return Observable.throw(error.json().error || 'servererror');
}
}
这是我的服务,我用这项服务在我的守卫
import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { IAppInfo } from './appInfo';
import { AppInfoService } from './appInfo.service';
@Injectable()
export class AppInfoResolveGuard implements Resolve<IAppInfo[]> {
appInfo : IAppInfo[];
errormessage : string;
constructor (private _appInfoService : AppInfoService ){
console.log("Resolve Guard");
}
resolve() {
console.log('guard'+this._appInfoService.getAppInfo());
return this._appInfoService.getAppInfo();
}
}
并将此解析传递到路由器路径
{ path: 'rklob', resolve: {app : AppInfoResolveGuard }, component: RklobAppComponent },
在我的组件类中获取数据
import { Component, OnInit } from '@angular/core';
import { Route } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { IAppInfo } from './appInfo';
import { AppInfoService } from './appInfo.service';
import { IWelcome } from './home/welcome';
@Component({
selector: 'rklob-app-main',
moduleId: module.id,
templateUrl: 'rklob-app.component.html'
})
export class RklobAppComponent implements OnInit {
appInfo : IAppInfo[];
appWelcome : IWelcome;
appAbout : IAbout;
appService : IServices[];
appPerson : IPerson[];
appClientGallery : IClientGallary[];
appPackage : IPackage[];
appAddresses : IAddress[];
errormessage : string;
constructor (private _route : ActivatedRoute, private _appInfoService : AppInfoService){
console.log('component');
}
ngOnInit(){
this.appInfo = this._route.snapshot.data['app'];
for(let data of this.appInfo){
console.log(data.captionData);
this.appWelcome.captionData = data.captionData;
this.appWelcome.welcomeInfo = data.welcomeInfo;
}
}
}
console.log(data.captionData);
显示一个值,但它可以指定给this.appWelcome.captionData
和this.appWelcome.welcomeInfo = data.welcomeInfo;
给我一个错误
异常:uncaught(in promise):typeerror:无法设置属性
未定义类型的“captionData”错误:无法设置属性
未定义的“captionData”
如何分配
this.appWelcome.captionData = data.captionData;
最佳答案
appWelcome
未初始化。您可以为其分配一个空对象,这将解决问题(请注意,您可能需要添加具有空值的属性,以便在编译时满足iwelcome接口的要求):
appWelcome : IWelcome = {};
关于http - Angular 2,ResolveGuard,Angular http,,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41711983/