如何使用均值堆栈在前端实现findbyid

时间:2018-07-23 11:08:32

标签: node.js angular mongodb

我的route.js

router.get('/:id',(req,res,next)=>{
  University.findById(req.params.id, function (err, universities){
     if(err)
     {
       res.json(err);
     }
     else{
       res.json(universities);
     }
  });
});

此后端过程运行良好。但是我不知道如何在有角度的前端中实现。

university.service.ts

getSingleuniversities(id)
  {
    return this.http.get('http://localhost:3000/api/' + id).map(res => res.json());
  }

我的singleuniversity.component.ts

import { Component, OnInit } from '@angular/core';
import {UniversityService} from '../university.service';
import {University} from '../university';

@Component({
  selector: 'app-singleuniversity',
  templateUrl: './singleuniversity.component.html',
  styleUrls: ['./singleuniversity.component.css']
})
export class SingleuniversityComponent implements OnInit {
  universities: University[];

  constructor(private universityService:UniversityService) { }

  ngOnInit() {}
  getSingleuniversities(id:any){
  this.universityService. getSingleuniversities(id)
        .subscribe( universities => 
        this.universities = universities);
      }
}

singleuniversity.component.html

<li>{{university.universityname}}</li>

在singleuniversity.component.html中,我收到了错误消息,

SingleuniversityComponent.html:1 ERROR TypeError: Cannot read property 'universityname' of undefined
    at Object.eval [as updateRenderer] (SingleuniversityComponent.html:1)
    at Object.debugUpdateRenderer [as updateRenderer] (core.js:10872)
    at checkAndUpdateView (core.js:10248)
    at callViewAction (core.js:10484)
    at execComponentViewsAction (core.js:10426)
    at checkAndUpdateView (core.js:10249)
    at callViewAction (core.js:10484)
    at execEmbeddedViewsAction (core.js:10447)
    at checkAndUpdateView (core.js:10244)
    at callViewAction (core.js:10484)

如何解决这个问题。我不知道我在哪里弄错了,如果有人知道,请帮助我。

1 个答案:

答案 0 :(得分:0)

如果我没记错的话,您的服务应该返回一个Observable,并且应该更像这样:

getSingleuniversities(id): Observable<University[]>{
    return this.http.get<University[]>('http://localhost:3000/api/' + id);
}

然后应按如下所示调用该方法:

this.universityService.getSingleuniversities(id).subscribe( 
 (universities: University[]) => this.universities = universities,
 (err: any) => console.log(err));
}

您的列表项应显示在这样的循环中:

<li *ngFor="let university of universities">{{university.universityname}}</li>

这样,列表在等待请求响应的过程中根本不显示任何项目,并且不应该抛出未定义的错误。