Joe Alvini
Joe Alvini

Reputation: 299

Use Observable In Angular To Get Information From Express API

I am new to Angular and struggling to figure out how I get information from my express API. I am simply trying to get a story from my story model in Express from Angular. Please note that if I request said story in Express it works. However I cannot figure out how to use Observable in Angular. Here is my code:

Express

models/stories.js

//Require Mongoose
const mongoose = require('mongoose');

//Define a schema
const Schema = mongoose.Schema;

const StorySchema = new Schema({
        title: String,
        body:String,
        author: String,
        date: Date,
        rating:Number,
        published:Boolean,
        tag:String},
    {collection: 'Stories'}
);
let Story = mongoose.model('Story', StorySchema );

module.exports = Story;

story.js (route):

  let express = require('express');
let router = express.Router();
let Story = require('../models/stories');
/* GET users listing. */
router.get('/:id', function(req, res) {
    let id = req.params.id;
    Story.findOne({_id:id}, (err, story) => {
        res.send({story:story});
    });
});

module.exports = router;

Angular

story.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';


export interface Story {
  id: String;
  name: String;
  body: String;
}

@Injectable({
  providedIn: 'root'
})
export class StoryService {

  constructor(private http: HttpClient)  { }

  getStory(id: string): Observable<Story> {
    return this.http.get<Story>('http://127.0.0.1:3000/story/' + id);
  }
}

home.component.ts

import { Component, OnInit } from '@angular/core';
import {Story, StoryService} from '../models/story.service';
import {Observable} from "rxjs";

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor() {

  }

  ngOnInit() {
  }

}

Now My problem is, what do I have to add to home.component to get a story to be viewed in the actual page? Any help would be greatly appreciated. Thanks.

Upvotes: 0

Views: 479

Answers (1)

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

Please look at the angular tutorial, it's really good. You may want to look here: https://angular.io/tutorial/toh-pt6

As an answer to your question, you can Inject the StoryService in your HomeComponent, so that you can use its methods.

export class HomeComponent implements OnInit {

   constructor(private _storyService: StoryService) {
       // inject in the constructor
       // the instance could be used in the component class with `this._storyService`
   }

   ngOnInit() {

   }

   // let's say that this method is fired whenever you want a new story
   // maybe on a button click from your HTML
   // requires an id parameter
   getMyStory(id: string) {
       this._storyService.getStory(id).subscribe((data) => {
           console.log(data);  // this is the data returned from your API
       })
   }

}

Upvotes: 2

Related Questions