【发布时间】:2019-03-26 04:22:01
【问题描述】:
我已经复制了本教程 https://malcoded.com/posts/angular-backend-express/ 来设置一个 Angular 应用程序和一个带有 Node.js 的快速服务器
我现在正尝试发送一个 GET 请求以使用以下代码检索对象数组:
import { Component, OnInit } from '@angular/core';
import { CatService } from './cat/cat.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'malcodedTutorial';
constructor(private catSerivce: CatService) { }
cats = [];
ngOnInit() {
const catsObservable = this.catSerivce.getAllCats();
catsObservable.subscribe((catsData: []) => {
this.cats = catsData;
});
console.log(this.cats);
}
}
另外,这里是 server.js 文件:
const express = require('express');
const app = express();
const cors = require('cors')
var corsOptions = {
origin: 'http://localhost:4200',
optionsSuccessStatus: 200
}
app.use(cors(corsOptions))
app.listen(8000, () => {
console.log('Server started!')
});
// GET ALL CATS
app.route('/api/cats').get((req, res) => {
res.send({
cats: [{ name: 'lilly' }, { name: 'lucy' }],
})
})
// GET A SPECIFIC CAT
app.route('/api/cats/:name').get((req, res) => {
const requestedCatName = req.params['name']
res.send({ name: requestedCatName })
})
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.route('/api/cats').post((req, res) => {
res.send(201, req.body)
})
// UPDATE
app.route('/api/cats/:name').put((req, res) => {
res.send(200, req.body)
})
// DELETE
app.route('/api/cats/:name').delete((req, res) => {
res.sendStatus(204)
})
另外,这是我的猫服务:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
interface Cat {
name: string;
}
@Injectable({
providedIn: 'root'
})
export class CatService {
constructor(private http: HttpClient) {}
getAllCats(): Observable<Cat[]> {
return this.http.get<Cat[]>('http://localhost:8000/api/cats');
}
getCat(name: string): Observable<Cat> {
return this.http.get<Cat>('http://localhost:8000/api/cats/' + name);
}
insertCat(cat: Cat): Observable<Cat> {
return this.http.post<Cat>('http://localhost:8000/api/cats/', cat);
}
updateCat(cat: Cat): Observable<void> {
return this.http.put<void>(
'http://localhost:8000/api/cats/' + cat.name,
cat
);
}
deleteCat(name: string) {
return this.http.delete('http://localhost:8000/api/cats/' + name);
}
}
当我运行 Angular 应用程序时,页面按预期显示,并且控制台中没有错误。
控制台记录了一个空数组,我不知道为什么应用程序没有从 server.js 中获取 cat 对象。
谁能告诉我哪里出错了?非常感谢
【问题讨论】: