Is there a way to execute a function on a Typescript model object within an Ionic HTML template? Whenever I try to do so, it triggers an error message saying
self.context.$implicit.myFunctionName is not a function
.
In my Ionic2 app, I am aiming to showcase images from the Flickr API. To generate the URL for a Flickr photo, one needs to combine multiple data fields from the API response and add a specific suffix denoting the desired photo resolution. This task is accomplished through the getUrl
function within the Photo
model.
src/models/photo.ts
export class Photo {
id: string;
owner: string;
secret: string;
server: string;
farm: number;
title: string;
url: string;
// Retrieve the URL for the photo at the specified suffix size.
// s - small square 75x75
// q - large square 150x150
// t - thumbnail, 100 on longest side
// m - small, 240 on longest side
// n - small, 320 on longest side
// - - medium, 500 on longest side ... etc
getUrl(suffix: string) {
return 'https://farm' + this.farm +
'.staticflickr.com/' + this.server +
'/' + this.id + '_' + this.secret + '_' + suffix + '.jpg';
}
}
The HTML template invokes getUrl('q')
for each photo in the returned set.
<div *ngFor="let photo of photos" class="photo-thumbnail">
<img [src]="photo.getUrl('q')" />
</div>
As a result, the following error emerges:
Uncaught Error: Error in ./PhotosPage class PhotosPage - inline template:13:9 caused by: self.context.$implicit.getUrl is not a function
Additional code:
src/pages/photos.ts
import { Component } from '@angular/core';
import { Photo } from '../../models/photo';
import { FlickrService } from '../../services/flickr.service'
@Component({
selector: 'page-photos',
templateUrl: 'photos.html'
})
export class PhotosPage {
photos: Photo[];
constructor(private flickrService: FlickrService) {
// Receive photo data from Flickr (this function is operating as intended)
flickrService.getPhotos().subscribe(photos => {
this.photos = photos;
});
}
}
services/flickr.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import { Photo } from '../models/photo';
@Injectable()
export class FlickrService {
constructor(public http: Http){}
// Fetch the initial 100 photos for a user (this function is functioning as expected)
getPhotos(): Observable<Photo[]> {
return this.http.get('https://api.flickr.com/path/to/api/call')
.map(res => <Photo[]>res.json().photos.photo);
}
}