Search code examples
angularangular2-servicestypescript2.0angular5

Function Context Changes and Cannot Recognize Local Variables


I am using a data service to pass data between sibling components. I am facing a problem in the data service where the context of the function changes when accessing the array and pushing data into there.

@Injectable()
export class PassDataProxy {

passedData = [];

constructor(
) { }

pushPassedData = (input) => {

    //I can see the data passed into the function from this console
    console.log("To push: " + JSON.stringify(input));

    //This is where things go south
    this.passedData.push(input);
}

getPassedData(input) {
    return Observable.of(this.passedData);
}

clearPassedData() {
    this.passedData = null;
}

}

I injected the dependency from the child component and called pushPassedData function, and I can see the data is passed successfully to the function from the console. But when you access the passedData array and run push function, it gives this error:

Error message

My guess is that the context is changed and it cannot recognize the array anymore so i used arrow function instead of normal function. Even then, I still had this error.

Thank you for your help.


Solution

  • I realized that I called clearPassedData before calling pushPassedData.

    There is nothing wrong with that but clearPassedData function should look like

    clearPassedData() {
        this.passedData = [];
    }
    

    I realized I was setting the variable to null instead of [] so it lost its array properties.