无法从HTML模板Angular 2中访问类中声明的变量

时间:2016-10-26 04:12:54

标签: angular typescript

首先,我知道我应该为此使用服务并计划,但我无法检索服务中的数据,所以我在我的组件中构建它。我无法从html模板访问“photos”变量。获取下面列出的错误。

import { Component } from '@angular/core';
import {HTTP_PROVIDERS} from '@angular/http';
import {PhotosComponentComponent} from './photos-component/photos-    component.component';
import {PhotosServiceService} from './photos-component/photos-    service.service';
// import {photos} from './photos-component/photo';
import {Observable} from 'rxjs/Rx';
import {Http, Response} from '@angular/http';

@Component({
  moduleId: module.id,
  selector: 'ang2demo-app',
  templateUrl: 'ang2demo.component.html',
  styleUrls: ['ang2demo.component.css'],
  providers: [PhotosServiceService, HTTP_PROVIDERS]    
})

export class Ang2demoAppComponent {

  title = 'ang2demo works!';

  constructor(private http: Http) {}


  private photosUrl = 'https://jsonplaceholder.typicode.com/photos';

  getPhotos(){

   this.http.get(this.photosUrl)
    .map((res:Response, data) => res.json())
    .subscribe(
      data => {
        let photos = data;
        console.log(photos);
        return photos; //Now this variable 'photos' contains all of my data from the http.get request. But, I cannot access it from the template - Below
      }
    )
  }



  ngOnInit() {
    this.getPhotos()
  }
}

这是我在templateUrl

中提供的模板代码
<div ngIf *ngFor="let photo of photos">{{photo.url}}</div>

我收到错误“无法读取未定义的url属性”。为什么我无法访问模板html中的photos变量?

2 个答案:

答案 0 :(得分:0)

正如您的代码现在一样,您不是将照片保存在控制器实例上,而是将其保存到模板中。

@Component({
  selector: 'my-app',
  template: `
    <div *ngFor="let photo of photos">{{photo.url}}</div>
  `,
})
export class App {
  photos: any[];
  private photosUrl = 'https://jsonplaceholder.typicode.com/photos';

  constructor(private http: Http) { }

  ngOnInit() {
    this.getPhotos()
  }

  getPhotos() {
    this.http.get(this.photosUrl)
      .map(data => data.json())
      .subscribe(data => {
        this.photos = data;
      });
  }
}

这是一个最小的plunker demonstrating the code

答案 1 :(得分:0)

与此战斗。我从组件中删除了这个逻辑并将其构建到Service中,我返回一个映射的Observable。我将它导入到我的组件中,并在我的构造函数中声明它之后从ngOnInit函数中引用它。

然后我使用* ngFor来迭代Observable并且仍然遇到问题,但是当迭代一个Observable时你必须使用异步管道#34;让照片的照片|异步&#34 ;.完成后,一切正常。

看起来在调用数组上的.subscribe方法时,它返回自己的范围,然后替换&#34的引用;这个&#34;。