【问题标题】:How does Angular or Typescript work?Angular 或 Typescript 是如何工作的?
【发布时间】:2018-07-12 00:23:06
【问题描述】:

我不确切知道 Angular 或 Typescript 是如何工作的,我认为在这段代码中,它应该是 3 1 2。但它是 1 2 3。请帮助我。

confirmDelete(id: number) {
    this.commentService.queryByStoryId(id).subscribe(
        (res: ResponseWrapper) => {
            this.comments = res.json;
            console.log(3);
        },
        (res: ResponseWrapper) => this.onError(res.json)
    );
    console.log(1);
    console.log(2);
    // for (let i = 0; i < this.comments.length; i++) {
    //     this.commentService.delete(this.comments[i].id);
    // }
    this.postService.delete(id).subscribe((response) => {
        this.eventManager.broadcast({
            name: 'postListModification',
            content: 'Deleted an post'
        });
        this.activeModal.dismiss(true);
    });
}

CodeConsole

【问题讨论】:

  • javascript 不阻止
  • 3 1 2 是正确的,因为 console.log(3) 将被处理。这意味着,这个 observable 需要被调用。我的情况是 1,2,然后是 eventManger.broadcast 或观察者呼叫的某个地方。在此处查看有关反应式编程的更多信息github.com/Reactive-Extensions/RxJS
  • @DaveClough:并不是说 JavaScript 不会阻塞;就是非阻塞的东西不会阻塞。

标签: angular typescript jhipster


【解决方案1】:

这是因为在 JavaScript(和 TypeScript)中,代码分为两类:

  • 同步码:

    代码自己同步执行,因为没有什么可等待的,你告诉他做某事,它就会做。

    这部分代码就是这种情况,只要你输入confirmDelete()方法就会执行:

代码部分:

 console.log(1);
 console.log(2);
  • 异步代码:

    有一些代码执行被延迟,因为您需要在执行自己的代码之前等待一些东西。

这就是这部分代码发生的事情:

代码部分:

this.commentService.queryByStoryId(id).subscribe(
  ...
);

你到达你的服务类CommentService,你需要同步执行方法queryByStory()。问题是,由于此方法可能(从其外观)执行对后端服务的 HTTP 调用,而您想要的是在收到响应后执行一些代码。

您看到的是来自库 RxJSsubscribe() 方法,它允许您在后端工作完成后捕获来自 HTTP 调用的响应。

这意味着subscribe() 方法中的所有内容都是一个异步执行的新函数——当响应准备好时。

所以这段代码是异步的,会在延迟后执行:

    this.eventManager.broadcast({
        name: 'postListModification',
        content: 'Deleted an post'
    });
    this.activeModal.dismiss(true);

这就是为什么你见证1 2 3 而不是3 1 2


但话说回来,你是一点一点地学习的,所以在尝试编写任何代码之前,先了解一下 JavaScript 是什么,这样你就会学到你所缺乏的基础知识。然后,在尝试使用其他库(例如 RxJS 和 observables)之前,您将了解 Promises 是什么是异步代码的基础知识。

我的意思是我们不能在这里教你这个,所以这取决于你。互联网上已经有很多关于这个主题的内容了。

【讨论】:

  • 感谢您的解释和建议。谢谢。
猜你喜欢
  • 2016-03-13
  • 1970-01-01
  • 2015-11-19
  • 2020-09-01
  • 2017-01-10
  • 1970-01-01
  • 2019-07-10
  • 1970-01-01
相关资源
最近更新 更多