我正在学习Angular 2,并且在尝试创建服务时遇到了此错误。我试着寻找解决方案,但我看不出自己的错误。
错误:
angular2-polyfills.js:1243 TypeError: Tweet is not a constructor
代码:
export class TweetService{
getTweets(){
return tweets;
}
}
let tweets = new Tweet("URL", "Author 1", "Handle 1", true, 50);
class Tweet {
image: string;
author: string;
handle: string;
status: "Lorem ipsum dolor sit amet.";
isLiked: boolean;
favorites: number;
constructor(img, aut, hndl, ilkd, fav){
img = this.image;
aut = this.author;
hndl = this.handle;
ilkd = this.isLiked;
fav = this.favorites;
}
}
答案 0 :(得分:2)
你的let语句在类声明之外浮动。这将有效(但在一个真实的应用程序中,你将根据一些http调用或其他东西设置你的推文):
import {Injectable} from '@angular/core';
@Injectable()
export class TweetService{
getTweets(){
let tweets = new Tweet("URL", "Author 1", "Handle 1", true, 50);
return tweets;
}
}
class Tweet {
image: string;
author: string;
handle: string;
status: "Lorem ipsum dolor sit amet.";
isLiked: boolean;
favorites: number;
constructor(img, aut, hndl, ilkd, fav){
this.image = img;
this.author = aut;
this.handle = hndl;
this.isLiked = ilkd;
this.favorites = fav;
}
}