0

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.

3 Answers 3

1
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

Error in your console

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

Sign up to request clarification or add additional context in comments.

7 Comments

I don't even get a print statement showing on the console when I do this.
@FernandoAnia console.log(this.blogArray) try this
didn't make a difference
@FernandoAnia any error in console. I guess you are not getting data from the service
No errors at all. You can follow the link to see the response mocky.io/v2/59a49eb3100000be05b2aba6. I also checked the response on postman and it is returning data.
|
0

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);

3 Comments

Same as I said to the other guy, when I try to console.log from the subscribe function nothing shows up in the chrome console
I don't have access to the fetch method as I am using the http class from @angular/http
@Fernando Ania Is your problem resolved? still need any help?
0

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);

  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.