简体   繁体   English

Angular HttpClient获取,此对象错误

[英]Angular HttpClient get, wrong this object

in my Angular App i make a simple call to a node.js server. 在我的Angular App中,我对node.js服务器进行了简单的调用。 the HttpClient "get" function returns the right answer. HttpClient的“ get”函数返回正确的答案。 This answer I want to store in a variable of my component "interfaces". 我想将这个答案存储在组件“接口”的变量中。 But in the "subscribe" function of the get request my "this" pointer doesn't point to my component. 但是在get请求的“ subscribe”功能中,“ this”指针未指向我的组件。 Instead it tells me that it is of type "SafeSubscriber". 相反,它告诉我它是“ SafeSubscriber”类型。 Any call to my member "interfaces" lead to the following error: TypeError: Cannot read property 'interfaces' of undefined 对我的成员“接口”的任何调用都会导致以下错误: TypeError:无法读取未定义的属性“ interfaces”

export class SettingsComponent implements OnInit {

public interfaces : string[];

constructor(private http: HttpClient) {
    this.interfaces = [];
    this.interfaces.push("huhu");

}

ngOnInit() : void {

    this.http.get('http://localhost:3000/settings/interfaces').subscribe((data) => {
        // Read the result field from the JSON response.
        console.log(data);
        this.interfaces.push("xxx");
        Object.keys(data).forEach(function(k) {
            console.log(k);
            this.interfaces.push("xxx");
        });
    }),
    err => {
      console.log("error " + err);
    }; 
}

} }

As you can see I also tried to enter some values manually into the array just to make sure, that not the server response is causing the problem. 如您所见,我还尝试将一些值手动输入到数组中,以确保不是服务器响应引起了该问题。 Any help is appreciated. 任何帮助表示赞赏。

I used this code as a blueprint which is from: https://angular.io/guide/http 我将此代码用作蓝图,来自: https : //angular.io/guide/http

@Component(...)
export class MyComponent implements OnInit {

  results: string[];

  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    // Make the HTTP request:
    this.http.get('/api/items').subscribe(data => {
      // Read the result field from the JSON response.
      this.results = data['results'];
    });
  }
}

You're losing reference to the correct this in this statement: 您在此语句中丢失了this正确的引用:

Object.keys(data).forEach(function(k) {..})

Inside the function block code this refers to the calling context , which is the subscribe method itself, that's why interfaces is undefined, since it's not a property of the subscribe method. 在功能块代码内部, this指的是调用上下文,这就是订阅方法本身,这就是为什么interfaces未定义的原因,因为它不是订阅方法的属性。

You can change the function for a lambda en it should be fine: 您可以更改lambda的函数,这样就可以了:

Object.keys(data).forEach((k) => {..})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM