在angular中,Subscribe函数会在组件中调用所有方法之后被调用,这导致我无法使用响应

我已经尝试用await和async来解决它,但作为新的打字脚本,我不习惯这些方法。

我已经使用await and a和async like是这样的:

async refreshList(){
 await this.service.refreshList().subscribe(res => {
   console.log(res);
   this.service.todoListModel=res;
   });
}

通过调试和控制台输出,我了解到subscribe方法参数代码是最后执行的。

请帮忙修改我下面的组件代码:

import { Component, OnInit } from '@angular/core';
import { groupBy } from '@progress/kendo-data-query';
import { moveDown, slideIn, slideOut } from '../animations';
import { TodoService } from '../todo.service';
@Component({
  selector: 'todo',
  templateUrl: './todo.component.html',
  styleUrls: ['./todo.component.css'],
  providers: [TodoService],
  animations: [
    trigger('todoAnimations',[
      transition(':enter',[
        group([
          query('h1', [
            useAnimation(moveDown)
          ]),
          query('input', [
            useAnimation(moveDown)
          ]),
          query('@todoItem', [
            stagger(125, animateChild())
          ]),
        ])
      ])
    ]),
    trigger('todoItem', [
      transition(':enter', [
        useAnimation(slideIn)
      ]),
      transition(':leave',[
        useAnimation(slideOut)
      ])
    ])
  ]
})
export class TodoComponent implements OnInit {
  
  constructor(public service:TodoService) {
    this.refreshList(); 
    console.log(this.service.todoListModel);
    
  }
  
  ngOnInit(): void {
    this.organizeTodosByHour();
  }
    refreshList(){
      this.service.refreshList().subscribe(res => {
        console.log(res);
        this.service.todoListModel=res;
        });
    }
  organizeTodosByHour(){
    do
    {
      if(!this.service.todos) return null;
      this.service.hourlyTodos=groupBy(this.service.todos,[{field: "hour"}]);
      console.log(JSON.stringify(this.service.hourlyTodos,null,2));
      return 0;
    }
    while(this.service.todoListModel===[])
  }
  public onTimeChange(t:any){
    t.hour=t.due.getHours();
    this.organizeTodosByHour();
    console.log(this.service.todos,this.service.hourlyTodos);
  }
  addTodo(input: HTMLInputElement){
    this.service.todos=[{item:input.value, due: new Date(), hour:(new Date()).getHours()},...this.service.todos];
    input.value='';
    this.organizeTodosByHour();
  }
  removeTodo(i:number){
    this.service.todos.splice(i,1);
    this.organizeTodosByHour();
  }
}

请帮我解决我的问题。这将非常有帮助,如果任何人可以解释给我如何使用等待和异步。

###如果你想使用async/await,你可以使用convert observable to promise。有一个正在使用但已弃用的方法toPromise instead use lastValueFrom.

而不是使用lastValueFrom.

import { lastValueFrom } from 'rxjs';
constructor(public service:TodoService) {
   (async () => {
         await this.refreshList();
         console.log(this.service.todoListModel);
   })();
  }
async refreshList(){
      const list$ = this.service.refreshList();
      this.service.todoListModel= await lastValueFrom(list$);;
}

对于特定的情况,还有其他util可观察函数,你应该查看这个链接以了解更多细节。

###感谢你们的努力,我终于明白了await and async methods and I ended up with the code b和async meth方法,我最后得到了下面的代码:

import { animateChild, group, query, stagger, transition, trigger, useAnimation } from '@angular/animations';
import { Component, OnInit } from '@angular/core';
import { groupBy } from '@progress/kendo-data-query';
import { moveDown, slideIn, slideOut } from '../animations';
import { TodoService } from '../todo.service';
import { lastValueFrom } from 'rxjs';
@Component({
  selector: 'todo',
  templateUrl: './todo.component.html',
  styleUrls: ['./todo.component.css'],
  providers: [TodoService],
  animations: [
    trigger('todoAnimations',[
      transition(':enter',[
        group([
          query('h1', [
            useAnimation(moveDown)
          ]),
          query('input', [
            useAnimation(moveDown)
          ]),
          query('@todoItem', [
            stagger(125, animateChild())
          ]),
        ])
      ])
    ]),
    trigger('todoItem', [
      transition(':enter', [
        useAnimation(slideIn)
      ]),
      transition(':leave',[
        useAnimation(slideOut)
      ])
    ])
  ]
})
export class TodoComponent implements OnInit {
  
  constructor(public service:TodoService) {
    this.refreshList(); 
    
  }
  
  ngOnInit(): void {
  }
  async refreshList(){
    const list$ = this.service.refreshList();
    this.service.todoListModel= await lastValueFrom(list$);
    console.log(this.service.todoListModel);
    this.service.todoListModel.forEach(element => {
      this.service.todos.push({item:element.itemName as string,due:(new Date(element.dueDate)),hour: (new Date(element.dueDate)).getHours()});
    });
    this.organizeTodosByHour();
}
  organizeTodosByHour(){
    if(!this.service.todos) return null;
      this.service.hourlyTodos=groupBy(this.service.todos,[{field: "hour"}]);
      console.log(JSON.stringify(this.service.hourlyTodos,null,2));
      return 0;
  }
  public onTimeChange(t:any){
    
    t.hour=t.due.getHours();
    this.organizeTodosByHour();
    console.log(this.service.todos,this.service.hourlyTodos);
    
  }
  addTodo(input: HTMLInputElement){
    this.service.todos=[{item:input.value, due: new Date(), hour:(new Date()).getHours()},...this.service.todos];
    input.value='';
    this.organizeTodosByHour();
  }
  removeTodo(i:number){
    this.service.todos.splice(i,1);
    this.organizeTodosByHour();
  }
}

###我看到你在构造函数中加载列表,但你也可以在解析器中加载列表,这样数据就会从一开始就出现在组件中,或者如果你想这么做,只需将Observable转换为Promise。

refreshList(): void {
    this.service.todoListModel =
       await this.service.refreshList().toPromise();
}
阅读全文

▼ 版权说明

相关文章也很精彩
推荐内容
更多标签
相关热门
全站排行
随便看看

错说 cuoshuo.com —— 程序员的报错记录

部分内容根据CC版权协议转载;网站内容仅供参考,生产环境使用务必查阅官方文档

辽ICP备19011660号-5

×

扫码关注公众号:职场神器
发送: 1
获取永久解锁本站全部文章的验证码