Angular 2 HTTP GET returning URL null

2019-06-24 02:04发布

问题:

I am trying to make a simple HTTP GET request using angular 2 with Typescript. I am getting a 404 error, with a null url. Shown below is my component file, and the error I am receiving.

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { BreadcrumbService } from './breadcrumbService';
import { Http, Response } from '@angular/http';

@Component({
  moduleId: module.id,
  providers: [ BreadcrumbService],
  templateUrl: 'html/appList.html',
  styleUrls: ['css/list.css']

})
export class HealthComponent {
  constructor(private http: Http) {
      this.http.get('http://jsonplaceholder.typicode.com/posts/1')
      .toPromise()
      .then((res: Response) => {
      console.log('RES: ', res);
      })
    .catch((err: Error) => {
      console.log('ERR!!: ', err);
    });
   }
}

The error message:

Response {_body: Object, status: 404, ok: false, statusText: "Not Found",     headers: Headers…}
 _body:Object
 headers:Headers 
 ok:false
 status:404
 statusText:"Not Found"
 type:2
 url:null
 __proto__:Body

回答1:

This is probably InMemoryWebApiModule.forRoot related issue. This happens when you load in-memory api, but trying to reach undefined url. The way to solve this is by setting passThruUnknownUrl: true in app.module config:

InMemoryWebApiModule.forRoot(InMemoryDataService, {passThruUnknownUrl: true}) ..



回答2:

As you can see, it's a 404 error, analyse your request to the server. 404 error means that what you requested wasn't found.

About how you make the request, try ti use .map instead of toPromise.

Try to not make HTTP requests on the constructor, use ngOnInit instead.



标签: http angular get