简体   繁体   中英

Angular 4 http not returning response

I have created a simple service to get data via a http request. The data is in json form and I use the map function so that it matches the Blog data type. However when I invoke the method "getBlogs" from the service to get the data nothing is returned. Any thoughts on what I am missing?

The Component.

import {Http} from '@angular/http';
import {forEach} from '@angular/router/src/utils/collection';
import {BlogService} from '../services/blog.service';
import {Component, OnInit} from '@angular/core';
import {Blog} from '../blog/blog';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';

@Component({selector: 'app-blog-list', templateUrl: './blog-list.component.html',
styleUrls: ['./blog-list.component.css'],
providers: [BlogService]})
export class BlogListComponent implements OnInit {

  blogArray: Blog[] = [];
  blogTitle: string;
  loading: boolean;
  private blogsUrl = 'http://www.mocky.io/v2/59a49eb3100000be05b2aba6';

  constructor(private blogService: BlogService, private http: Http) {}

  ngOnInit() {
    this.blogService
      .getBlogs(this.blogsUrl)
      .subscribe(res => {
        this.blogArray = res;
        console.log('theBlogArray', this.blogArray);
      });
  }

}

The Service

import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';
import {Headers, Http } from '@angular/http';
import { Injectable } from '@angular/core';
import {Blog} from '../blog/blog';

@Injectable()
export class BlogService {


  private loading: boolean;
  constructor(private http: Http) {}


  getBlogs(url: string): Observable<Blog[]> {
    this.loading = true;
    return this.http.get(url)
      .map((response) => response.json());
  }

}

As mentioned in the answers it might be a CORS issue. However, I do not get any errors at all in the console. Just in case I enabled the CORS chrome extension (it's called Allow-Control-Allow-Origin: *) on my browser, which is what I usually do when I have CORS issues and I made sure to put it in the header of mocky, again as suggested. Nothing yet, no complain from the console and webpack compiles successfully.

If I hard code the values of the json request into an array in the service an access it via component, the values are returned and I can console.log them and display them on the html.

ngOnInit() {
    this.blogService.getBlogs(this.blogsUrl)
      .subscribe(res => {this.blogArray = res;
console.log('theBlogArray: ', this.blogArray);// this will work and use it in template like{{blogArray}}
);


  }

You are getting the data the only thing is that you are console logging it outside as it is a async call you cannot log in synchronous context.

Update

控制台错误

I tried this same url using angular it is giving some CORS issue there is something wrong with the backend there please check console. you will get error

The console print outside of the subscription will not wait for response.So try like

ngOnInit() {
    this.blogService.getBlogs(this.blogsUrl)
        .subscribe(res => {
           this.blogArray = res;
           console.log('theBlogArray: ', this.blogArray);
    }, Err => console.log(Err));
}

.

// Service   
import 'rxjs/add/operator/catch';

return this.http.get(url)
  .map((response) => response.json())
  .catch(Err);

The reason why I was not seeing the response from the http request was because I was making a reference to the blog-list component inside the main app component without importing blog-list in the main app component.

I was doing this

<app-nav-bar></app-nav-bar>
<app-blog-list></app-blog-list>

Which required me to do this

import { Component } from '@angular/core';
import { BlogListComponent } from './blog-list/blog-list.component';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'app';
    }

I am still unsure why I am able to access the value of the hard coded array from the service and not from the http request without importing blog-list.component into the main app.

blog.service

public blogExample: Blog;
  private loading: boolean;

  constructor(private http: Http) {
    this.blogExample = {
      id: 1,
      title: 'title',
      content: 'content'
    };
  }

blog-list.component

ngOnInit() {
    this.blogService
      .getBlogs(this.blogsUrl)
      .subscribe(res => {
        this.blogArray = res;
        console.log('theBlogArray', this.blogArray);
      });

    console.log('blogExample', this.blogService.blogExample);

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM