简体   繁体   English

无法从Angular的响应数据分配数据

[英]unable to assign data from response data in Angular

I have a function that should return an array of objects when called. 我有一个函数,应在调用时返回对象数组。 The function looks like this 该功能看起来像这样

loadTodo(): Todo[]{
var data 
this.http.get(`${this.API_URL}todos`).toPromise().then(res => {
  data = res.json()
  }, error => {
    console.log(error)
  })
  return data}

This results in unexpected behavior where data variable gets assigned correctly inside the success response block but is undefined when accessed outside the response block. 这会导致意外的行为,其中在成功响应块内正确分配了data变量,但在响应块外访问时undefined

The function is assigned to a variable with type Todo[] and is invoked immediately when the variable is declared. 该函数被分配给类型为Todo[]的变量,并在声明该变量时立即调用。 I am quite new to TypeScript and Angular but not to JavaScript. 我对TypeScript和Angular很陌生,但对JavaScript却不是。 Am I missing something with scope/closure of the function or is this issue related to TypeScript/Angular? 我是否在函数范围/关闭方面缺少某些内容,或者此问题与TypeScript / Angular有关?

Whole class looks like this: 全班看起来像这样:

export class TodoDataService {
  API_URL: String = 'http://localhost:3000/'  
  todos: Todo[] = this.loadTodo();
  constructor(private http: Http) {
  }
  loadTodo(): Todo[]{
    this.http.get(`${this.API_URL}todos`).toPromise().then(res => {
      this.parcedTodos = res.json()
      console.log('inside function')
      console.log(this.parcedTodos)
      }, error => {
        console.log(error)
      })
      console.log('outside function')
      console.log(this.parcedTodos)
      return this.parcedTodos
  }
}

It is happening because http calls are asynchronous . 这是因为http调用是asynchronous

You need to make sure you are accessing data only after call is completed. 您需要确保仅在通话完成后才访问数据。

export class TodoDataService {
  API_URL: String = 'http://localhost:3000/'  
  todos: Todo[] = this.loadTodo();
  constructor(private http: Http) {
  }
  loadTodo(): Todo[]{
    this.http.get(`${this.API_URL}todos`).toPromise().then(res => {
      this.parcedTodos = res.json()
      console.log('inside function')
      console.log(this.parcedTodos)
      }, error => {
        console.log(error)
      },
      {
        console.log(this.parcedTodos);
        // This is where your call gets completed. Here you can access assigned data or call another function where you can access data.
      })
      console.log('outside function')
      console.log(this.parcedTodos) // This is called before asynchronous call is completed. Thats why it is undefined yet.
      return this.parcedTodos
  }
}

Hope this helps. 希望这可以帮助。

I think that using res.json() not is neccesary because angular pipes already doing this works. 我认为不是必须使用res.json()因为有角度的管道已经可以工作了。 Do you try to assign to variable res directly? 您是否尝试直接分配给变量res?

As others friends says, you are doing bad some things. 就像其他朋友说的那样,您在做某些事情上做得不好。

First: you must read about asynchronous methods 首先:您必须了解异步方法

Second: use Observables importing rxjs/Observable; 第二:使用Observables导入rxjs / Observable; and follow its callbacks flow 并遵循其回调流程

Example

    export class TodoDataService {
  API_URL: String = 'http://localhost:3000/'  
  todos: Todo[] = this.loadTodo();
  constructor(private http: Http) {
  }
  loadTodo() : Observable<Todo[]>{
    return this.http.get(`${this.API_URL}todos`);
  }
}

And other class consummes this method 其他类使用此方法

 todoDataService.loadTodo().subscribe(
        (response) => {
          console.log("Future response", response);
        }
    );

http.get() is asynchronous, which means that when you try to print parcedTodos outside the then callback, it will still be undefined. http.get()是异步的,这意味着当您尝试在then回调之外打印parcedTodos ,它将仍然是未定义的。

Asynchronous programming in JS JS中的异步编程

this.http.get(whatever) is an async call. this.http.get(whatever)是一个async调用。 Your data is undefined because you're accessing it before it is actually initialized. 您的dataundefined因为您需要在实际初始化之前访问它。 ie you're initializing it inside the success handler (the first argument to then ), and probably are accessing it before initialization. 也就是说,您正在success处理程序( then的第一个参数)内部对其进行初始化,并且可能在初始化之前对其进行了访问。

All you need to do is make sure you're doing so after the success or error handler. 您需要做的就是确保successerror处理程序之后执行此操作。 use Observable 使用Observable

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

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