0

I'm having problems setting a member variable on an ng2 component. In the component below, I'm trying to set some service results to a member variable. updateSearchResults1() sets the member variable as expected but updateSearchResults2 delegates the promise to processSearchResults which returns the error: "TypeError: Cannot set property 'blogPostListItems' of null." My understanding was that these 2 implementations were functionally the same. So why can I set this.blogPostListItems from updateSearchResults1() whereas I get an error that this.blogPostListItems is null from updateSearchResults2()?

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Router } from '@angular/router';
import { BlogService } from '../../services/blog.service';
import { BlogLanding } from '../../entities/blog-landing';
import { Response } from '@angular/http';

@Component({
    selector: 'blog-landing',
    templateUrl: '../../../ng2/templates/blog-landing.component.html'
})

export class BlogLandingComponent implements OnInit
{
    @ViewChild('ddlAuthor') ddlAuthor;
    blogLanding: BlogLanding;
    blogPostListItems: Array<Object>;

    constructor(
        private router: Router,
        private blogService: BlogService){}

    ngOnInit(): void
    {
    }

    updateSearchResults1()
    {
        this.blogService
            .getBlogPosts()
            .then(blogPostListItems => this.blogPostListItems = blogPostListItems)
    }

    updateSearchResults2()
    {
        this.blogService
            .getBlogPosts()
            .then(this.processSearchResults);
    }

    processSearchResults(responseObject)
    {
        this.blogPostListItems = responseObject;
    }

}
user8334943
  • 1,467
  • 3
  • 11
  • 21
  • Because in the 2nd case you are passing the function without context of current object (`this`). You can use something like `.then(this.processSearchResults.bind(this))` to make it works. – Harry Ninh Jul 28 '17 at 00:25
  • @HarryNinh would that work without also taking it as a parameter in the method? I would always use an [arrow function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions) to solve this – 0mpurdy Jul 28 '17 at 00:45
  • @0mpurdy yes it will. I myself prefer arrow function too, but it's good to know that there's more than one way to skin the cat. And actually learning about `bind` helps me understand more about JS callbacks/events. – Harry Ninh Jul 28 '17 at 01:06
  • @HarryNinh ah of course I completely missed the fact that you had `.bind()` there! I didn't know about that thanks :) [This question](https://stackoverflow.com/questions/2236747/use-of-the-javascript-bind-method) was helpful – 0mpurdy Jul 28 '17 at 01:09

0 Answers0