简体   繁体   中英

Angular 2 - Unable to assign return value from http subscribe() method to a global variable inside component

I am getting a JSON file using http.get in angular 2.

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 is an array of JSON objects. I'm trying to store selected data from this.allFiles to this.images. I would also like to access this.images as a global variable throughout my component but haven't been able to do so because of async calls with http.get(). I did try the async pipe within my html but that also led to an error. Is there a way to access this.images globally?

Thanks in advance.

I have little experience with TypeScript and Angular2 but I guess that your problem is with the arrow functions and the this keyword. Whenever you use brackets on an error function the this inside of it starts referencing the function itself, and not the desired upper class. Do the same for your error handling as well.

Also remove the call from your constructor and use ngOnInit for that.

Please try something like this and let me know:

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

Where do you want to access the this.allFiles ?

You can add that to the template without any pipe because it's inside of subscribe from Observables, Angular2 knows to re-render the template and it will be updated.

If you need to access in other function from the component, then add the function calls inside the .subscribe function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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