首页 > 解决方案 > 在 Angular 中使用 Observable 从 Express API 获取信息

问题描述

我是 Angular 的新手,正在努力弄清楚如何从我的 express API 中获取信息。我只是想从 Angular 的 Express 中的故事模型中获取一个故事。请注意,如果我在 Express 中请求所说的故事,它会起作用。但是我不知道如何在 Angular 中使用 Observable。这是我的代码:

表达

模型/故事.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(路线):

  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;

故事服务.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() {
  }

}

现在我的问题是,我必须添加什么到 home.component 才能在实际页面中查看故事?任何帮助将不胜感激。谢谢。

标签: angular

解决方案


请看角度教程,真的很好。你可能想看这里:https ://angular.io/tutorial/toh-pt6

作为您问题的答案,您可以StoryService在您的 中注入HomeComponent,以便您可以使用它的方法。

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
       })
   }

}

推荐阅读