Thanks so much Sander, this was very helpful.
Regards,
Rich
On Thursday, October 26, 2017 at 11:33:29 PM UTC-6, Sander Elias wrote:
>
> Hi Rich,
>
> First of all, your typing is off. At least the type any[] does not relate
> to your template where you are using an Object.
> Also, subscribing in the service as you are doing it, is not needed.
> Let me show you some of my example code:
>
> @Component({
> selector: 'app-movie',
> template: `
> <h1>Movie Component</h1>
>
> <button (click)="previousMovie()">Previous</button>
>
> <div *ngIf="currentMovie | async as movie; else noMovie" >
> ({{movie.id}}) {{movie.title }}
> </div>
>
> <ng-template #noMovie>
> <div><i>No Movie</i></div>
> </ng-template>
>
> <button (click)="nextMovie()">Next</button>
> <button routerLink="/">Home</button>
> `,
> providers: [ FilmService ],
> styleUrls: ['./movie.component.css']
> })
> export class MovieComponent implements OnInit {
> private currentId: number;
> public currentMovie: Observable<Movie>;
> private routerEventsSubscription: Subscription;
>
> constructor(
> private filmService: FilmService,
> private route: ActivatedRoute,
> private router: Router
> ) {}
>
> ngOnInit(): void {
> // Get new movie whenever the URL's id changes
> this.currentMovie = this.route.paramMap
> .switchMap(params => {
> const id = +params.get('id');
> return this.filmService.getFilm(id)
> .do(movie => this.currentId = movie.id)
> });
> }
>
> nextMovie() {
> this.currentId = this.currentId ? this.currentId + 1 : 1;
> this.router.navigate([`/movie/${this.currentId}`]);
> }
>
> previousMovie() {
> this.currentId = this.currentId ? this.currentId - 1 : 1;
> this.router.navigate([`/movie/${this.currentId}`]);
> }
> }
>
>
> This sample does a some more as what you are asking about, but it shows
> you how to avoid subscribing in your component, and how to prevent
> the error you are having. the ngIf prevents the content from rendering
> until there is actually a movie loaded from the service. It even shows you
> how to use the else, to show a loading/not found message to the user.
>
> If you have any more questions, just ask!
>
> Regards
> Sander
>
--
You received this message because you are subscribed to the Google Groups
"Angular and AngularJS discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.