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");
}