Angular 2 HTTP GET returning URL null

2019-06-24 02:36发布

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

标签: http angular get
2条回答
贼婆χ
2楼-- · 2019-06-24 03:00

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}) ..

查看更多
聊天终结者
3楼-- · 2019-06-24 03:07

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.

查看更多
登录 后发表回答