簡體   English   中英

Angular 2-無法將http subscription()方法的返回值分配給組件內部的全局變量

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

我在angular 2中使用http.get獲取一個JSON文件。

最近服務:

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

    }

}

最近的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?

提前致謝。

我對TypeScript和Angular2的經驗很少,但是我想您的問題是箭頭功能和this關鍵字。 每當在錯誤函數上使用方括號時,其內部的this便開始引用該函數本身,而不是所需的上層類。 還要對錯誤進行同樣的處理。

還要從構造函數中刪除該調用,並ngOnInit使用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;
    }
}

您想在哪里訪問this.allFiles

您可以將其添加到模板中, 而無需任何管道,因為它位於Observables的訂閱內部,Angular2知道可以重新渲染模板,並且它將被更新。

如果您需要從組件訪問其他函數,請在.subscribe函數內部添加函數調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM