It’s finally time to introduce some Http CRUD implementation! Today on the show we use yesterday mock in-memory RESTful Http service to get(), post(), and put() our way to remote data!

You can always grab tagged source code on the GitHub repo which will be tagged day1, day2, etc.

You can Subscribe to my Fresh Bytecode channel for regular Java/Web-related screencasts, or if you’re just into Angular, checkout the YouTube Playlist where I update all the episodes in this series as they come out.

Here’s the script so you can follow along at home:

[ ] Implement our getCurrentFeed() method

private getTweetFromJson(obj: Tweet): Tweet {
    return new Tweet(
      obj.id, obj.body, obj.author, obj.date, obj.retweets, obj.favorites)
  }

  getCurrentFeed(): Observable<Tweet[]> {

    return this.http.get('/api/tweets').map((resp: Response) => {
      console.log(resp.json());
      var fetchedTweets = [];
      for (let tweet of resp.json().data) {
        fetchedTweets.push(this.getTweetFromJson(tweet));
      }
      return fetchedTweets as Array<Tweet>;
    });

  }

[ ] Update feed.component.ts to handle the observable

this.feedService.getCurrentFeed().subscribe( (newTweets) => {
  console.log(newTweets);
    this.tweets = newTweets;
});

[ ] Demo of changing our database file.

[ ] Next, we’ll update our service to handle posting a new tweet as a JSON object

postNewTweet(tweetText: string) {

    let body = JSON.stringify({
      body: tweetText, author: this.userService.getCurrentUser(),
      date: new Date(), retweets: [], favorites: []
    });


    return this.http.post('/api/tweets', body).map(
      (resp: Response) => {
        console.log(resp.json());
        return this.getTweetFromJson(resp.json().data);
      });

  }

[ ] Update our feed.componoent.ts to subscribe to the create..

OnNewTweet() {
    console.log(this.tweetText);
    this.feedService.postNewTweet(this.tweetText).subscribe(
      (newTweet : Tweet) => {
        console.log(newTweet);
        this.tweets.unshift(newTweet);
      });
    this.tweetText = '';
  }

[ ] Finally, update our service to handle updates..

updateTweet(tweet: Tweet) {
    let body = JSON.stringify(tweet);

    let url = `/api/tweets/${tweet.id}`;

    return this.http.put(url, body).map(
      (resp: Response) => {
        console.log(resp);
        if (resp.status == 204) {
          console.log("Success. Yay!");
        }
      });

}

[ ] Update retweet and favorite routines in service with an update call

this.updateTweet(tweet).subscribe(resp => console.log(resp));

[ ] Let the winning flow!!!

[ ] Next up we’ll start looking into HTTP Error Handling