【问题标题】:Property assignment not working in Angular service [duplicate]属性分配在 Angular 服务中不起作用 [重复]
【发布时间】:2017-09-21 22:36:07
【问题描述】:

我在 TypeScript 中为 Angular 4 提供了一个非常简单的可注入服务。它从网络获取 JSON 文件作为数组。之后,它应该将返回的数组存储在其属性之一中,称为data。然后data 可以被其他类使用getData() 方法访问。

我的问题是赋值操作被忽略了。执行this.data = data 实际上并没有改变this.data。其他一切都运行良好。

服务代码:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class JsonFetcherService {
  private data: any;

  constructor(private http: HttpClient) {
    this.data = null;
  }

  public fetch(url: string): void {
    this.http.get(url).subscribe(this.setData);
  }

  private setData(data) {
    this.data = data;
  }

  public getData(): any {
    return this.data;
  }
}

使用服务的一个非常简单的类的代码:

import { Component } from '@angular/core';

import { JsonFetcherService } from '../jsonFetcherService/JsonFetcherService';

@Component({
    selector: 'json-fetcher-example',
    templateUrl: './JsonFetcherExample.html'
})
export class JsonFetcherExample {
    constructor(private json: JsonFetcherService) {
        this.json.fetch('http://mysafeinfo.com/api/data?list=englishmonarchs&format=json');
    }
}

更新:

除了this的绑定问题外,这里使用的方法subscribe是异步的。获取 JSON 文件后要执行的代码需要移到回调中。

public fetch(url: string, myFunction) {
  const test = this.http.get(url);
  test.subscribe((data)=> {
    this.data = data;
    myFunction();
  });
}

【问题讨论】:

  • .subscribe(this.setData); 应该是 .subscribe((data)=>this.setData(data));.subscribe(this.setData.bind(this));。如果在编写回调时省略括号 (),您将丢失回调中的全局 this
  • @echonax 问题的主要原因实际上是this 的上下文和异步调用的组合,您标记的副本仅部分解决了问题。
  • 所以第二部分变成了stackoverflow.com/questions/14220321/…的副本:-)

标签: angular typescript this


【解决方案1】:

这里的这个问题是“this.data”的“this”的上下文。在 this.setData() 函数内部,“this”实际上是指可观察对象。试试这个来解决它:

let setData = (data)=> {
  this.data = data;
}

使用箭头表示法允许“this”上下文保留在类中,而不是 observable。

更多信息 Arrow Notation

【讨论】:

  • 谢谢。不确定你的意思。当我第一次遇到问题时,我正在使用箭头符号。我做到了:this.http.get(url).subscribe((data)=> { this.data = data; });。我不确定我应该把let放在哪里。
  • this.http.get(url).subscribe((data)=> { this.data = data; }); 应该可以工作,this.http.get(url).subscribe(this.setData); 不应该。
  • @Louis-MarieMatthews 要么按照 Harry 的建议去做,要么按照我的回答将 setData 函数定义更改为变量。除非您使用箭头符号,否则每个函数都有一个“this”。
  • 也许你期待这样的this.http.get(url).subscribe((data) => this.setData(data)); 使用箭头符号
  • 实际上,问题是双重的:我没有使用数组表示法,并且该方法是异步的。这意味着在this.data = data 之前调用了console.log。本来我是用箭头符号的,但是因为不知道方法是异步的,所以我尝试用标准方法代替,这就是我上面代码sn-p中贴出的方法。
猜你喜欢
  • 1970-01-01
  • 2014-11-03
  • 1970-01-01
  • 2018-07-05
  • 1970-01-01
  • 2020-04-01
  • 2019-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多