2

I am learning Angular 2 and I ran into this error while trying to create a service. I tried searching for a solution, but I cannot see my mistake.

Error:

angular2-polyfills.js:1243 TypeError: Tweet is not a constructor

Code:

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;        
    }
}
6
  • I've check your code here typescriptlang.org/play and all compiles fine Commented May 28, 2016 at 10:09
  • Just clutching at straws here but did you try to export the Tweet class? Commented May 28, 2016 at 11:03
  • @VasiliyVanchuk Which makes is strange. :) Commented May 28, 2016 at 11:12
  • @Oli I don't think that is the problem. I tried it, but it didn't fix it. Commented May 28, 2016 at 11:12
  • Ok, then we can rule that out atleast. Commented May 28, 2016 at 11:23

1 Answer 1

2

Your let statement is floating outside the class declarations. This will work (but in an real app you would be setting your tweets based on some http call or something):

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;        
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

You are correct sir. This fixed the issue. About the http calls, I am currently learning Angular 2 and local repositories are more practical. Once I get better, I will use a RESTful API. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.