角度“解析...期间HTTP失败”错误

时间:2018-08-12 09:16:09

标签: angular

我一直在尝试学习部署MEAN应用程序,我使用过 ng build 命令,该应用程序似乎运行正常,除了在必须检索数据的地方从数据库中(我正在使用mlab),而是显示此错误:

  

消息:“ http://localhost:8080/tickets / ticketList解析期间Http失败”

这是我的代码:

ticket-list.component.ts

import { Component, OnInit } from '@angular/core';
import{ UserService } from '../user.service';
import { HttpClient } from '@angular/common/http';


@Component({
  selector: 'app-ticket-list',
  templateUrl: './ticket-list.component.html',
  styleUrls: ['./ticket-list.component.css']
})
export class TicketListComponent implements OnInit {
li:any;

  constructor(private test:UserService) { }

del(x){
  console.log(x);
  this.test.deleteTicket(x);
}

  ngOnInit() {
    this.test.getTicketList().subscribe(data=>{
      this.li = data;
    })
  }

}

user.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { stringify } from '@angular/compiler/src/util';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  constructor(private http:HttpClient) { }

  getTicketList(){

   return this.http.get("tickets/ticketList", {responseType: 'text'});

    }
}

html文件

<div class="ticketList">
<table>
  <th>Event Name</th>
  <th>Title</th>

  <tr *ngFor="let d of li; let i = index">
    <td>{{d.eventName}}</td>
    <td>{{d.title}}</td>
    <td class="view"><a routerLink="/extendedList" routerlinkActive="active">view</a></td>
    <td class="delete"><a (click)="del(d.eventName)"> delete</a></td>

  </tr>
</table>
</div>

1 个答案:

答案 0 :(得分:0)

尝试:

getTicketList(){
  return this.http.get("tickets/ticketList", this.setHttpHeader());
}

setHttpHeader() {
  const headers = new HttpHeaders().set('Accept', 'application/json').set('Content-Type', 'application/json');
  let options = { headers: headers};
  return options;
}

不用说:有了HttpClientModule ,我们不需要在接收到之后解析数据。它会自动完成。