我已经复制了本教程https://malcoded.com/posts/angular-backend-express/,以设置带有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)
})
此外,这是我的Cat服务:
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对象。
有人可以告诉我我要去哪里吗?非常感谢
答案 0 :(得分:1)
您用于从服务器获取响应的代码是正确的。记录空数组的原因是您的console.log不在订阅中。由于可观察对象异步运行,因此它在接收到响应之前正在记录日志。如果您只希望在收到响应后将其作为console.log,则将其移至.subscribe()
内如果将ngOnInit()更改为以下形式,则在收到响应之前,您将不会console.log,因此除非响应中不包含任何猫,否则它不应再为空。
ngOnInit() {
const catsObservable = this.catSerivce.getAllCats();
catsObservable.subscribe((catsData: []) => {
this.cats = catsData;
console.log(this.cats);
});
}
这也可以:
export class AppComponent implements OnInit {
title = 'malcodedTutorial';
constructor(private catSerivce: CatService) { }
cats = [];
ngOnInit() {
this.getCats();
}
getCats() {
const catsObservable = this.catSerivce.getAllCats();
catsObservable.subscribe((catsData: any[]) => {
this.cats = catsData;
console.log(this.cats);
});
}
}
答案 1 :(得分:0)
我认为您永远不会从服务器获取数据。
使用猫服务
import { HttpHeaders } from '@angular/common/http';
getAllCats() {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': `Bearer test}`
});
const options = { headers: headers };
const url = 'http://localhost:8000/api/cats';
return this.http.get<Cat[]>(url, options);
}
首先,必须确保获得一些数据,并且控制台中的列表不为空。
否则,如果您获得了数据,并且模板中没有任何显示,请尝试查看init
您必须添加ngAfterViewInit
export class AppComponent implements OnInit, AfterViewInit {
title = 'malcodedTutorial';
constructor(private catSerivce: CatService) { }
cats = [];
ngOnInit() {
this.getCats();
}
ngAfterViewInit() {
this.getCats();
}
getCats() {
const catsObservable = this.catSerivce.getAllCats();
catsObservable.subscribe((catsData: any[]) => {
this.cats = catsData;
});
console.log(this.cats);
}
}