I am following this link on how to use service to make http request in Angular and update my list of items in a component. I can successfully do it with fat arrow function as obserable callback. But when I try to use a method in my component, it failed to update the list of items.
for example:
import { Component, OnInit } from '@angular/core';
import { BlogService } from '../blog.service';
import { Blog } from '../blog';
import { Observable, of } from 'rxjs';
@Component({
selector: 'app-articles',
templateUrl: './articles.component.html',
styleUrls: ['./articles.component.css']
})
export class ArticlesComponent implements OnInit {
blogs: Blog[];
constructor(private blogService: BlogService) { }
ngOnInit() {
// const handler = (incomingBlogs: Blog[]) => {
// this.blogs = incomingBlogs;
// console.log("we get: ", this.blogs);
// }
const observable: Observable<Blog[]> = this.blogService.getBlogs();
// observable.subscribe(handler); <===== this will work
// observable.subscribe(incomingBlogs => {this.blogs = incomingBlogs; console.log("fat get: ", this.blogs);}); <====== this also work
observable.subscribe(this.handler); // <===== this failed.
console.log("this in init", this);
}
handler(incomingBlogs: Blog[]) {
this.blogs = incomingBlogs;
console.log("we get: ", this.blogs);
console.log("this in handler", this); //seems the this keyword refers to something different than the object itself.
}
}
I tried three approaches to update the list of blogs
fat arrow inside the subscribe as callback. this works!
define a constant and assign a fat arrow function to it. pass it to subscribe function. It works too, just like option 1. And I understand as they behave the same.
define a method in the same class (the component). Use it as callback for the subscribe function. The method is called. But
this
keyword does not seem to refer to a component. Why is it different? I understand that in the world of javascript, function keyword gives you a whole differentthis
. But why does it happen in a method of a class in TypeScript? Why does thethis
mean different objects here? Why does fat arrow work ?
I have searched for the answers before but get no luck. (I must haven't used the correct keywords). Thanks for your help!