【发布时间】:2016-09-13 18:54:48
【问题描述】:
我正在使用 angular 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?
提前致谢。
【问题讨论】:
-
要使某些东西成为“全局”,您可以创建一个具有静态成员和存储的共享组件/模块,并在所有其他组件中使用 if。