首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角形:为什么我不能使用组件的一个方法作为一个可观察的回调来更新组件中的属性?

角形:为什么我不能使用组件的一个方法作为一个可观察的回调来更新组件中的属性?
EN

Stack Overflow用户
提问于 2018-08-26 02:11:44
回答 1查看 85关注 0票数 0

我正在跟踪此链接关于如何使用服务以角的形式发出http请求,并更新组件中的项目列表。我可以成功地使用fat箭头函数作为可观察的回调。但是,当我试图在组件中使用一个方法时,它无法更新项目列表。

例如:

代码语言:javascript
复制
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.
  }

}

我尝试了三种方法来更新博客列表。

  1. fat箭头内的订阅作为回调。这行得通!
  2. 定义一个常量并为其分配一个胖箭头函数。把它传递给订阅函数。就像选项1一样,我理解他们的行为也是一样的。
  3. 在同一个类(组件)中定义方法。将其用作订阅函数的回调。这个方法被调用。但是this关键字似乎并不是指组件。为什么不一样?我了解到,在javascript的世界中,函数关键字提供了一个完全不同的this。但是为什么在TypeScript中的类的方法中会发生这种情况呢?为什么this在这里意味着不同的对象?为什么脂肪箭会起作用?

我以前找过答案,但没有运气。(我肯定没有使用正确的关键字)。谢谢你的帮忙!

EN

回答 1

Stack Overflow用户

发布于 2018-08-26 02:21:05

Fat箭头函数总是绑定到在其中定义的对象,函数将绑定到从其中调用的对象。将处理程序更改为箭头函数。

代码语言:javascript
复制
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.
  }

如果在当前函数中放置一个断点,您将看到这指向可观察到的调用。

如果要使用正常函数,可以将其作为参数传递进来。

代码语言:javascript
复制
  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.
  }

但是我的建议是不要订阅控制器中的可观察性,并在您的视图中使用异步管道。

代码语言:javascript
复制
blogs$ = this.blogService.getBlogs();

在你的TypeScript和你的视野中

代码语言:javascript
复制
<ng-container *ngIf="blogs$ | async as blogs">
    Use blogs here as you would have before
    {{blogs | json}}
</ng-container>

然后,您就有了为您管理订阅的视图,而不必担心孤儿订阅。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52022660

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档