簡體   English   中英

Angular 4 http不返回響應

[英]Angular 4 http not returning response

我創建了一個簡單的服務來通過http請求獲取數據。 數據為json格式,我使用map函數,使其與Blog數據類型匹配。 但是,當我從服務中調用方法“ getBlogs”以獲取數據時,不會返回任何內容。 對我想念的東西有什么想法嗎?

組件。

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

}

服務

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

}

如答案中所述,這可能是CORS問題。 但是,我在控制台中根本沒有得到任何錯誤。 以防萬一我在瀏覽器上啟用了CORS chrome擴展名(稱為Allow-Control-Allow-Origin:*),當我遇到CORS問題並確保將其放在模擬標頭中時,通常這樣做再次建議。 沒什么,控制台也沒有抱怨,Webpack編譯成功。

如果我將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}}
);


  }

您獲取數據的唯一原因是您正在控制台將數據記錄到外部,因為它是異步調用,您無法在同步上下文中登錄。

更新

控制台錯誤

我嘗試使用角度相同的URL,它給了一些CORS問題,后端有問題,請檢查控制台。 你會得到錯誤

訂閱外的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);

我之所以沒有看到來自http請求的響應,是因為我在主應用程序組件內部引用了博客列表組件,而沒有在主應用程序組件中導入博客列表。

我在做這個

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

哪個需要我這樣做

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';
    }

我仍然不確定為什么如果不將blog-list.component導入主應用程序,為什么能夠從服務而不是從http請求訪問硬編碼數組的值。

blog.service

public blogExample: Blog;
  private loading: boolean;

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

博客,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