Angular 2 HTTP GET returning URL null

你说的曾经没有我的故事 提交于 2020-01-03 15:35:43

问题


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.



来源:https://stackoverflow.com/questions/39650686/angular-2-http-get-returning-url-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!