-1

I'm learning Angular 11 and Typescript and I'm getting an error that I don't understand. I've got a callback function in a service that seems to successfully return a string. I want to add that to another string that's declared in my class but I get the following error: TypeError: Cannot set property 'test' of undefined. I know that I'm probably doing the callback wrong but why does it successfully write the response to console but not to the variable "test"?

Here is my class:

export class AppComponent  implements OnInit  {
    test: string;

    constructor(private testService: TestService) { }

    ngOnInit(): void {
        this.testService.test(function(response: string) {
            console.log(response); //this bit is fine
            this.test = response; //this returns an error
        });
    }
}

And in my service:

test(callback) {
    callback("foo");
}
Simon
  • 47
  • 5
  • Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – R. Richards Nov 30 '20 at 00:43

2 Answers2

1

Use arrow functions :

this.testService.test((response: string) =>  {
    console.log(response); //this bit is fine
    this.test = response; //this returns an error
});

Although I would say that this method of callback is a little strange. Because you are using Angular, it's much more common to use RxJS to subscribe to observables and handle the callback yourself.

MindingData
  • 11,924
  • 6
  • 49
  • 68
1

Use the arrow function like this.

 test: string | undefined ;

 constructor(private testService: TestService) { }

 ngOnInit(): void {

 this.testService.test((response: string) => {
 this.test = response;  });
 }

Or else you can do this using RXJS as follows

service class

import { Observable, of } from 'rxjs';

test(): Observable<any> { return of('foo') }

component class

 test: string | undefined ;

 ngOnInit(): void {this.stackService.test().subscribe(res => this.test = res);}
Dinuka Ekanayake
  • 614
  • 8
  • 11