Angular 2 - 无法将http subscribe()方法的返回值赋给组件内的全局变量

时间:2016-09-13 18:54:48

标签: json http angular get

我在角度2中使用http.get获取JSON文件。

recent.service.ts:

import { Http, Response } from '@angular/http';
//import { Observable } from '../../../../../../node_modules/rxjs/Observable';
import { Observable } from '../../../../../../node_modules/rxjs/Rx';
import { Injectable } from '@angular/core';



@Injectable()
export class RecentService {

    private _url = 'http://localhost:3001/api/uploadedFiles';

    constructor(private _http: Http) {


    }

    getJson() {

        return this._http.get(this._url)
            .map(res => res.json());

    }

}

recent.component.ts:

    import {Component, OnInit} from '@angular/core';
    import {CORE_DIRECTIVES, FORM_DIRECTIVES, NgClass, NgStyle} from             '@angular/common';
    import {RecentService} from './recent.service';
    import {HTTP_PROVIDERS} from '@angular/http'; 
    import {Observable} from 'rxjs/Observable';


   @Component({
    selector: 'recent',
    pipes: [],
    providers: [RecentService, HTTP_PROVIDERS],
    styleUrls: ['/app/pages/content/components/recent.styles.css'],   //might need to change reference   
    template: require('./recent.html') // `<strong>My edit page</strong>`
   })
   export class Recent implements OnInit{

      allFiles;
      public allFiles_error:Boolean = false;
      openModalWindow:boolean=false;
      images = [];
      currentImageIndex:number;
      opened:boolean=false;
      imgSrc:string;

   constructor(private _recentService: RecentService) {
       this._recentService.getJson()
           .subscribe(data => { 
             this.allFiles = data;
             console.log("allFiles: ", this.allFiles);
             console.log(this.allFiles.length);
             for(var i = 0; i < this.allFiles.length; i++) {
               this.images.push({
               thumb: this.allFiles[i].url,
               img: this.allFiles[i].url,
               description: "Image " + (i+1)
              });
             }
             console.log("Images: ", this.images);
            },
           err => { this.allFiles_error = true },
           () => console.log('Completed!')
    );

  }

  ngOnInit() {

    console.log(this.images.length);
    console.log(this.images);
    console.log(typeof this.images);
  }
    //this is the function where I want to access this.images
    openGallery(index) {
      if(!index) {
        this.currentImageIndex = 1;
      }
      this.currentImageIndex = index;
      this.opened = true;
      for (var i = 0; i < this.images.length; i++) {
         if (i === this.currentImageIndex ) {
         this.imgSrc = this.images[i].img;
         break;
       }
    }
    console.log(this.imgSrc);
  }

this.allFiles是一个JSON对象数组。我正在尝试将this.allFiles中的选定数据存储到this.images。我还想在整个组件中访问this.images作为全局变量,但由于使用http.get()进行异步调用而无法这样做。我确实在我的html中尝试了异步管道,但这也导致了错误。有没有办法在全球范围内访问this.images?

提前致谢。

2 个答案:

答案 0 :(得分:2)

我对TypeScript和Angular2的经验不多,但我想你的问题在于箭头函数和this关键字。每当在错误函数上使用括号时,它内部的this开始引用函数本身,而不是所需的上层类。对错误处理也一样。

同时从构造函数中移除调用并使用ngOnInit

请尝试这样的事情让我知道:

export class Recent implements OnInit{
    allFiles;
    public allFiles_error:Boolean = false;
    openModalWindow:boolean=false;
    images = [];
    currentImageIndex:number;
    opened:boolean=false;
    imgSrc:string;

    constructor(private _recentService: RecentService) { }

    ngOnInit() {
        this._recentService.getJson().subscribe(
            data => initData(data),
            err => handleError(),
            () => console.log('Completed!'));
    }

    initData(data){
        this.allFiles = data;
        console.log("allFiles: ", this.allFiles);
        console.log(this.allFiles.length);
        for(var i = 0; i < this.allFiles.length; i++) {
            this.images.push({
            thumb: this.allFiles[i].url,
            img: this.allFiles[i].url,
            description: "Image " + (i+1)
            });
        }
        console.log("Images: ", this.images);
        console.log(this.images.length);
        console.log(this.images);
        console.log(typeof this.images);
    }

    handleError() {
        this.allFiles_error = true;
    }
}

答案 1 :(得分:0)

您想在哪里访问 this.allFiles

你可以将它添加到模板没有任何管道,因为它在Observables的subscribe中,Angular2知道重新渲染模板并且它将被更新。

如果您需要从组件访问其他功能,请在 .subscribe 功能中添加功能调用。