简体   繁体   English

Angular 4 http不返回响应

[英]Angular 4 http not returning response

I have created a simple service to get data via a http request. 我创建了一个简单的服务来通过http请求获取数据。 The data is in json form and I use the map function so that it matches the Blog data type. 数据为json格式,我使用map函数,使其与Blog数据类型匹配。 However when I invoke the method "getBlogs" from the service to get the data nothing is returned. 但是,当我从服务中调用方法“ getBlogs”以获取数据时,不会返回任何内容。 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. 如答案中所述,这可能是CORS问题。 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. 以防万一我在浏览器上启用了CORS chrome扩展名(称为Allow-Control-Allow-Origin:*),当我遇到CORS问题并确保将其放在模拟标头中时,通常这样做再次建议。 Nothing yet, no complain from the console and webpack compiles successfully. 没什么,控制台也没有抱怨,Webpack编译成功。

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. 如果我将json请求的值硬编码到服务中的数组中,并通过组件对其进行访问,则将返回这些值,我可以进行console.log它们并将它们显示在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. 我尝试使用角度相同的URL,它给了一些CORS问题,后端有问题,请检查控制台。 you will get error 你会得到错误

The console print outside of the subscription will not wait for response.So try like 订阅外的console print将不等待响应,因此请尝试

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. 我之所以没有看到来自http请求的响应,是因为我在主应用程序组件内部引用了博客列表组件,而没有在主应用程序组件中导入博客列表。

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-list.component导入主应用程序,为什么能够从服务而不是从http请求访问硬编码数组的值。

blog.service blog.service

public blogExample: Blog;
  private loading: boolean;

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

blog-list.component 博客,list.component

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

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

  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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