簡體   English   中英

Angular:為什么我不能使用組件的方法作為可觀察的回調來更新組件的屬性?

[英]Angular: why can't I use a method of my component as an obserable callback to update properties in the component?

我正在關注此鏈接 ,了解如何使用服務在Angular中發出http請求並更新組件中的項目列表。 我可以使用胖箭頭功能作為可觀察的回調成功完成此操作。 但是,當我嘗試在組件中使用一種方法時,它無法更新項目列表。

例如:

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. 訂閱中的粗箭頭作為回調。 這可行!

  2. 定義一個常量並為其分配一個粗箭頭功能。 傳遞給訂閱功能。 它也可以工作,就像選項1一樣。據我所知,它們的行為相同。

  3. 在同一類(組件)中定義一個方法。 用作預訂功能的回調。 該方法被調用。 但是this關鍵字似乎並不指向組件。 為什么不同? 我了解在javascript的世界中,function關鍵字this提供了完全不同的this 但是,為什么它會在TypeScript中的類方法中發生? 為什么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.
  }

如果在當前函數中放置一個斷點,您將看到它指向從中調用的可觀察對象。

如果您想使用普通功能,可以將其作為參數傳遞

  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>

然后,您便可以使用視圖為您管理訂閱,而不必擔心孤立訂閱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM