我无法使用mongoose从mongoDB(MEAN应用程序)中检索项目列表。 我想检索数据库中存在的每个对象(及其属性),然后将结果保存到对象的本地数组中。
我的后端工作正常,使用邮递员或本地主机,我可以看到检索到的数据作为JSON对象。但是我似乎无法将其保存到数组中。
后端部分:App.js:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
let ObjectId = require('mongoose').Types.ObjectId;
const Player = require('./Model/player');
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', "*");
res.setHeader('Access-Control-Allow-Headers', "Origin, X-Requested-Width, Content-Type, Accept")
res.setHeader('Access-Control-Allow-Methods', "GET, POST, PATCH, PUT, OPTIONS");
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/api/players', (req, res, next) => {
Player.find((err, docs) => {
if (!err) {
console.log(docs)
res.send(docs)}
else { console.log("Error : " + JSON.stringify(err, undefined, 2)) }
});
});
前端:我的播放器型号:
export interface IPlayer {
_id:string,
username: string;
rank: number;
score: number;
status:string;
time: string;
fGame: string;
}
players-service(从数据库中检索结果:
import { IPlayer } from './player.model';
import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';
import { HttpClient } from "@angular/common/http";
@Injectable({ providedIn: 'root' })
export class PlayersService {
public playersArr: IPlayer[]=[];
private playersUpdated = new Subject<IPlayer[]>();
selectedPlayer: IPlayer;
constructor(private http: HttpClient) {
}
getPlayers():Observable<IPlayer[]> {
const result = this.http.get<IPlayer[]>('http://localhost:3000/api/players');
console.log(result);
return result;
};
最后,播放器列表组件:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { IPlayer } from '../player.model';
import{ PlayersService } from '../players.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-player-list',
templateUrl: './player-list.component.html',
styleUrls: ['./player-list.component.css']
})
export class PlayerListComponent implements OnInit{
players : IPlayer[] = [];
private postsSub: Subscription;
constructor(public playS : PlayersService) { }
ngOnInit() {
this.playS.getPlayers()
.subscribe(data =>
this.players=data);
}
}
所以我的问题是在这里,数组“玩家”保持为空。 我尝试过分配它,然后再将其发送到列表组件,仍然一无所获 有任何想法吗 ?