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.
