首页 > 解决方案 > getContacts 无法从 Web 服务器获取信息

问题描述

我是Node JSExpress JSAngular JS的初学者,我正在尝试开发一个联系人应用程序,在服务器端编程我正在使用运行良好的Node JSExpress JS,我正在使用MONGO DB作为我的数据库,我的服务器端编程与我测试过的邮递员一起工作正常,

对于客户端编程的开发,我使用的是Angular JS,所以我在这里做了什么,创建新的应用程序“客户端”,然后再生成一个组件联系人,然后生成服务联系人。还有“从@angular/core 导入http ”。所以直到我在contacts.component.html中编程并通过选择器app-contact在app.component.html中显示它,我能够在我的网页上得到它并且工作正常。但是当我试图从网络服务器获取联系信息失败时,我没有收到任何特定错误,但在网页上什么也没有出现。

特别是当我在我的联系人组件中创建构造函数并传递参数私有联系人服务:像这样的“构造函数(/私有联系人服务:联系人服务/){}”这样的联系人服务时,它甚至会消失所有本地信息,如“标题”

/私人联系服务:ContactService /

===============================contact.ts================= ==========

    export class Contact{
    _id?: string;
    first_name: string;
    last_name: string;
    phone: string;}

============================contact.service.ts================= ====

   import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';
import {Contact} from './contact';
import 'rxjs/add/operator/map';


@Injectable() 
 
export class ContactService {

  contacts: Contact[];

 constructor(private http: Http) { }

 getContacts()
 {
   return this.http.get("http://localhost:3000/api/contacts").map(res => res.json());
 }
 
 addContact(newContact)
 {
   var headers = new Headers();
   headers.append('Content-Type','application/json');
   return this.http.post('http://localhost:3000/api/contact', newContact, { headers: headers })
     .map(res => res.json());
 }

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

===============================contacts.component.ts=============== =====

import { Component, OnInit } from '@angular/core';
import {ContactService} from '../contact.service';
import { Contact } from '../contact';

@Component({
 selector: 'app-contacts',
 templateUrl: './contacts.component.html',
 styleUrls: ['./contacts.component.css'],
 providers: [ContactService]
})
export class ContactsComponent implements OnInit {

 contacts: Contact[];
 contact: Contact;
 first_name: string;
 last_name: string;
 phone: string;

 constructor(private contactService: ContactService) { }


   ngOnInit() : void
   {
     
       this.contactService.getContacts()
         .subscribe(contacts =>
         this.contacts = contacts);   
     }
 }

======================contacts.component.html===================

    
<h2>contacts works!</h2>

<div class = "container">
    <div *ngFor = "let contact of contacts">
      <div class = "col-md-3">
        {{contact.first_name}}
      </div>
      <div class = "col-md-3">
          {{contact.last_name}}
      </div>
      <div class = "col-md-3">
          {{contact.phone}}
      </div>   
    </div>
  </div>

=================================app.component.html============= =====

<app-contacts><app-contacts>

这是我所有的代码。

标签: javascriptnode.jsangularjstypescriptexpress

解决方案


我假设逻辑中的所有内容都是正确的,因为您提到没有错误。div在这种情况下,您可以使用以下部分环绕您ngFor

*ngIf="contacts && contacts.length"

确保它在渲染之前存在。让我知道这是否适合你。


推荐阅读