我正在跟踪此链接关于如何使用服务以角的形式发出http请求,并更新组件中的项目列表。我可以成功地使用fat箭头函数作为可观察的回调。但是,当我试图在组件中使用一个方法时,它无法更新项目列表。
例如:
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.
}
}我尝试了三种方法来更新博客列表。
this关键字似乎并不是指组件。为什么不一样?我了解到,在javascript的世界中,函数关键字提供了一个完全不同的this。但是为什么在TypeScript中的类的方法中会发生这种情况呢?为什么this在这里意味着不同的对象?为什么脂肪箭会起作用?我以前找过答案,但没有运气。(我肯定没有使用正确的关键字)。谢谢你的帮忙!
发布于 2018-08-26 02:21:05
Fat箭头函数总是绑定到在其中定义的对象,函数将绑定到从其中调用的对象。将处理程序更改为箭头函数。
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.
}如果在当前函数中放置一个断点,您将看到这指向可观察到的调用。
如果要使用正常函数,可以将其作为参数传递进来。
handler(incomingBlogs: Blog[], controller: ArticlesComponent) {
controller.blogs = incomingBlogs;
console.log("we get: ", controller.blogs);
console.log("this in handler", controller); //seems the this keyword refers to something different than the object itself.
}但是我的建议是不要订阅控制器中的可观察性,并在您的视图中使用异步管道。
blogs$ = this.blogService.getBlogs();在你的TypeScript和你的视野中
<ng-container *ngIf="blogs$ | async as blogs">
Use blogs here as you would have before
{{blogs | json}}
</ng-container>然后,您就有了为您管理订阅的视图,而不必担心孤儿订阅。
https://stackoverflow.com/questions/52022660
复制相似问题