angular - 在 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 才能在实际页面中查看故事?任何帮助将不胜感激。谢谢。
解决方案
请看角度教程,真的很好。你可能想看这里: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
})
}
}
推荐阅读
- swift - 如何同时将多个项目添加到字符串列表
- mysql - MYSQL 插入触发器(插入多个值)
- rinsim - 如何跟踪消息通过 PDPModel 遵循的路径?
- php - cURL - 如何将 PDF 文件发送到 SFTP 服务器
- android - 启用 proguard 后出现 StackOverflow 错误
- python - 在 defaultdict 中使用标签编码器时如何获取 Labelencoder.Classes_?
- angular - 在 angular-5 中的锚标记单击事件中调用函数打开提交 html 表单的新选项卡
- regex - oracle在varchar2列中查找并添加前缀和后缀
- php - 如何在php中禁用反引号运算符?
- mysql - 如何找到多个最大计数