当我编译我的角度2项目时,我面临以下错误。我是角度2的新手,似乎无法得出关于分辨率的结论。我搜索SO上的线程类似于此但它不起作用。
此错误出现在我正在进行的多个服务调用中。它是一个MEAN堆栈应用程序。请看一下截图....
代码:
this.authService.gettodaysmatches().subscribe((data:any) => {
console.log("Data for today's matches coming up Admin panel...");
console.log(data);
this.todaysMatches = data;
//this.matchId = this.todaysMatches._id;
for(var i=0; i<this.todaysMatches.length; i++){
var hometeam = this.todaysMatches[i].hometeam.teamname;
var awayteam = this.todaysMatches[i].awayteam.teamname;
var obj = {};
obj.hometeam = hometeam;
obj.awayteam = awayteam;
obj.matchid = this.todaysMatches[i]._id;
this.todaysTeam.push(obj);
}
})
答案 0 :(得分:1)
您可以为todaysMatches
- TodaysMatches 创建自定义类型并投射它:
this.authService.gettodaysmatches().subscribe((data:TodaysMatches) => {
<...>
或使用Typescript的查找类型和访问属性,例如 - ['prop']
:
this.authService.gettodaysmatches().subscribe((data:any) => {
this.todaysMatches = data;
for(var i=0; i<this.todaysMatches.length; i++){
var hometeam = this.todaysMatches[i]['hometeam']['teamname'];
var awayteam = this.todaysMatches[i]['awayteam']['teamname'];
<...>
P.S。错误的屏幕截图显示了一堆与您发布的代码段无关的其他与Typescript相关的错误
答案 1 :(得分:0)
您可以这样做:
// Api returned Type
export interface MatchModel{
id: number;
title: string;
hometeam: string;
}
// Light Model.
export interface OtherModel {
id: Number;
title: string;
}
@Injectable()
export class ApiService {
/**
* Dummy observable to fake Api answer. Return Array of MatchModel
*/
getDummyData(): Observable<MatchModel[]> {
return Observable.create((obs) => {
obs.next([
{
id: 1,
title: "foo",
hometeam: "bar"
},
{
id: 2,
title: "ksdof",
hometeam: "koko"
},
{
id: 3,
title: "fokokoo",
hometeam: "sdfsdf"
}
]);
});
}
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
providers: [ApiService],
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
public matchs: MatchModel[];
public others: OtherModel[];
constructor(private api: ApiService) {
this.matchs = [];
this.others = [];
}
ngOnInit() {
this.api.getDummyData().subscribe(matchs => {
this.matchs = matchs;
// We just map array of MatchModel to fit on OtherModel type.
this.others = this.matchs.map(match => {
return {
id : match.id,
title: match.title
};
});
console.log(this.matchs, this.others);
});
}
}