user3296193 user3296193 - 1 month ago 7
TypeScript Question

inputing data with angularjs 2 using services

So I'm learning angularjs 2 and having trouble understanding the uses of service and getting it to work with my app.

film.services.ts

import { Injectable } from "@angular/core";

import { Film } from './film';
import { FILMS } from './mock-films';

@Injectable()
export class FilmService {
getFilms(): Promise<Film[]> {
return Promise.resolve(FILMS)
}
}


mock-films

import { Film } from './film';

//storing the data in array
export const FILMS: Film[] = [
{id:11, title: 'pokemon', summary:'great'},
{id:12, title: 'naruto', summary: 'good'},
{id:13, title: 'bleach', summmary: 'meh'},
{id:14, title: 'one piece', summary: 'not bad'}
];


film-list.components.ts

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable'
import { FilmService } from '../film.service';
import { Film } from "../film";

@Component({
template: `
<h1>List of Films</h1>
<p>Films:</p>
<ul>
<li *ngFor="let film of films ">
<a [routerLink]="['/films', film.id]">{{film.title}}</a>
</li>
</ul>
<p *ngIf="films.length > 3">There are many vietnamese films to learn about!</p>
`,
// important when adding to service other crashes
providers: [FilmService]
})

//Component class
export class FilmListComponent implements OnInit {
public films: Film[];
constructor(private filmService: FilmService) {}

getFilms(){
this.filmService.getFilms().then((films: Film[]) => this.films = films);
}

ngOnInit():any {
this.getFilms()
}
}


so my goal is getting the data from my mock-films into my film list but it is not showing up for some reason. It probably the film-list.component.ts but not sure where the error is.

Answer

fix in here

  public films: Film[]=[];

OR

public films: Film[];
  constructor(private filmService: FilmService) {}
     getFilms(){
        this.flims=[];
        this.filmService.getFilms().then((films: Film[]) => this.films = films);
      }

film-list.components.ts

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable'
import { FilmService } from '../film.service';
import { Film } from "../film";

@Component({
  template: `
  <h1>List of Films</h1>
  <p>Films:</p>
  <ul>
    <li *ngFor="let film of films ">
     <a [routerLink]="['/films', film.id]">{{film.title}}</a>
      </li>
  </ul>
  <p *ngIf="films.length > 3">There are many vietnamese films to learn about!</p>
`,
  // important when adding to service other crashes
  providers: [FilmService]
})

//Component class
export class FilmListComponent implements OnInit {

  public films: Film[];
  constructor(private filmService: FilmService) {}

  getFilms(){

    this.flims=[];//fix in here
    this.filmService.getFilms().then((films: Film[]) => this.films = films);
  }

  ngOnInit():any {
    this.getFilms()
  }
}
Comments