Angular 损失 var/const

Angular loss of var/const

我正在 angular(确切地说是 5)中制作一个简单的 rest todo-crud 应用程序。

我在范围方面有问题(或者更确切地说是问题)(或者​​我认为这就是问题所在):

home.component.ts :

import { Component, OnInit } from '@angular/core';
import { HomeService } from './service/home.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  itemCount: number = 0;
  todo = [];
  addingVar: Object;
  dueDate: string;
  constructor(private homeService: HomeService) { }

  ngOnInit() {
    let ltodo = []; // ADDED THIS TO FORCE VALUE STORAGE
    this.homeService.getToDo().subscribe(
      function(response) {
        ltodo = response;
      },
      function(error) { console.log('Error happened', error); },
      function() { }
    );
    setTimeout(function(){ // <-HACK TO FORCE IT TO STORE DATA AT LEAST WITHIN "ngOnInit"
                           // I'LL USE A DEBOUNCED FUNCTION INSTEAD LATER
      this.todo = ltodo;
      this.itemCount = this.todo.length;
      console.log(this.todo);      // <- (array of 9 objects) works!!
      console.log(this.itemCount); // <- 9                    works!!
    }, 10);
  }

  addItem() {
    console.log(this.todo); // <- this.todo IS NOW EMPTY ARRAY! WHY??
    this.addingVar = {name: this.todoTitle, description: this.todoText, date: Date.now(), dueDate: this.dueDate };
    console.log(this.addingVar);
    this.homeService.postToDo(this.addingVar).subscribe(
      function(response) { console.log('Success Response', response); },
      function(error) { console.log('Error happened', error); },
      function() { }
    );
  }
}

home.service.ts :

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class HomeService {
  constructor (
    private http: Http
  ) {}
  getToDo() {
      return this.http.get(`http://localhost:3000/todos`)
        .map((res: Response) => res.json());
  }
  getToDoId(id: string) {
    return this.http.get(`http://localhost:3000/todos/${id}`)
      .map((res: Response) => res.json());
  }
  postToDo(body: object) {
    return this.http.post(`http://localhost:3000/todos`, body)
      .map((res: Response) => res.json());
  }
  putToDoId(id: string, body: object) {
    return this.http.put(`http://localhost:3000/todos/${id}`, body)
      .map((res: Response) => res.json());
  }
  deleteToDoId(id: string) {
    return this.http.delete(`http://localhost:3000/todos/${id}`)
      .map((res: Response) => res.json());
  }
}

我不知道我应该如何使用 vars/lets/const

我做错了什么?为什么,在我的第一个函数(应用程序加载后立即调用)中,我有一个 hydrated var 而在我的第二个函数中(必须在之后调用,因为我必须单击一个按钮才能调用它),是我的 var 没有水合??? :

还有为什么我被迫做这个本地 var + wait/debounce 噱头来从响应函数中获取响应?

一定有更好的方法。

在 ngOnInit 中,您的应用不会等待 forthis.homeService.getToDo() 结束。它运行其余的方法,只要您的请求完成,它就会运行您订阅的功能。 所以 this.todo = ltodo; 在获取结果之前被调用。

您在回调中输掉了 this。您需要使用箭头函数或将 this 绑定到您的回调。

setTimeout(() => { // <-HACK TO FORCE IT TO STORE DATA AT LEAST WITHIN "ngOnInit"
                           // I'LL USE A DEBOUNCED FUNCTION INSTEAD LATER
      this.todo = ltodo;
      this.itemCount = this.todo.length;
      console.log(this.todo);      // <- (array of 9 objects) works!!
      console.log(this.itemCount); // <- 9                    works!!
    }, 10);`

setTimeout((function(){ // <-HACK TO FORCE IT TO STORE DATA AT LEAST WITHIN "ngOnInit"
                       // I'LL USE A DEBOUNCED FUNCTION INSTEAD LATER
  this.todo = ltodo;
  this.itemCount = this.todo.length;
  console.log(this.todo);      // <- (array of 9 objects) works!!
  console.log(this.itemCount); // <- 9                    works!!
}).bind(this), 10);

会做你需要的。 箭头函数可以访问父上下文,而 function(){} 声明不能毫无障碍地这样做。

您不需要使用 setTimeout 来等待服务器的响应,事实上,在您的 subscribe 中您已经检索到值,所以只需:

ngOnInit() {
this.homeService.getToDo().subscribe(
  response => this.todos = response // sufficient
  error =>  console.log('Error happened', error) // use lamdas to preserve `this`
  }