gpt4 book ai didi

javascript - Angular 2 : Promise return

转载 作者:行者123 更新时间:2023-12-03 06:22:45 26 4
gpt4 key购买 nike

我想从我的 API 获取评论。那么,函数应该 promise 返回吗?什么是更好的?经典还是 promise 回归?

我还有一个问题, promise 返回未定义。

comments.component.ts

import { Component, OnInit } from '@angular/core';
import { CommentService } from '../services/comment.service';
import { Comment } from '../class/Comment';

@Component({
template: 'dadada',
providers: [CommentService]
})

export class CommentsComponent implements OnInit {
coms: Comment[];

constructor(private commentService: CommentService) {
}

ngOnInit() {
console.log( this.commentService.testfunction() );

this.commentService.get_all_comments().then((data) => {
this.coms = data;
});
console.log ( this.commentService.get_all_comments2() );
console.log ( this.coms );
}
}

comment.service.ts

import { Injectable } from '@angular/core';
import { Comment, Comments } from '../class/Comment';

@Injectable()
export class CommentService {
testfunction() {
return 'valoare';
}
get_all_comments() {
return Promise.resolve(Comments);
}
get_all_comments2() {
return Comments;
}
}

评论.ts

export class Comment {
id: number;
text: string;
author: string;
created_at: number;
updated_at: number;
}

export const Comments: Comment[] = [
{id: 1, text: 'Look I am a test comment.', author: 'Chris Sevilleja', created_at: 0, updated_at: 0}
];

我在控制台中得到这些:

valoare

Array [ Object ]

undefined

最佳答案

您需要将代码移至 then(...) 内(对于具有 subscribe(...) 的可观察量也是如此

ngOnInit() { 
console.log( this.commentService.testfunction() );

this.commentService.get_all_comments().then((data) => {
this.coms = data;
console.log ( this.commentService.get_all_comments2() );
console.log ( this.coms );
});
}

Promisethen(...) 的目的是启用链接调用,以便在前一个调用完成时执行后续调用。

异步执行意味着调用将被排入事件队列,然后执行同步代码(您的 console.log())。传递给 .then(...) 的代码最终会在 Promise 解析时执行(通常是在服务器响应到达时)。

关于javascript - Angular 2 : Promise return,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38793849/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com