In this scenario, I intended to use a service for retrieving data but encountered difficulties. As a result, I developed the functionality within my component instead. Despite successfully obtaining the 'photos' variable through an HTTP request, I encountered issues accessing it from the HTML template, which led to the error mentioned below.
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; //The 'photos' variable now holds all retrieved data from the HTTP GET request. However, I am unable to access it from the template as shown below.
}
)
}
ngOnInit() {
this.getPhotos()
}
}
The following snippet illustrates my template code referenced in the templateUrl:
<div ngIf *ngFor="let photo of photos">{{photo.url}}</div>
An error message stating "cannot read url property of undefined" arises. Why does the photos variable prove inaccessible from the template's HTML?