首页 > 解决方案 > NgOnInit 没有在服务订阅中执行代码

问题描述

这是我的NgOnInit方法。在控制台中只执行“hello before”。我试过做.subscribe( () => console.log("hello after")),但里面没有任何工作。

    ngOnInit(): void {
    console.log("hello before")
    this.checkoutService.getTemplates().subscribe(({ templates }) => {
      console.log("hello after")
      this.templates = templates;
      console.log(templates)
    })
  }

结账服务:

     getTemplates(): Observable<{templates: Template[]}> {
        return this.http.get<{templates: Template[] }>("http://localhost:3000/checkout")
      }

/结帐端点处理程序:

    router.get("", (req, res, next) => {
        var templates = [];
        var realTemps = [];
        const token = req.headers.authorization.split(" ");
        const decoded = jwt.verify(token[1], 'secretkey');
        decodedFactoryId = decoded.factoryId
    
        Template.findAllByFactoryId(decodedFactoryId)
            .then((results) => {
                for (var i = 0; i < results.length; i++) {
                    // THIS IS AN AVOIDABLE LOOP, quadratic time must be prevented by correctly formatting the data (TODO)
                    for (var j = 0; j < results.length; j++) {
                        if (results[i][j].id) {
                            templates.push(results[i][j].id)
                        }
                    }
                }
            }).then(() => {
                // Promise.all
                return Promise.all(templates.map(template => Template.findByTemplateId(template).then(result => {
                    console.log("here is the result: " + JSON.stringify(result[0]))
                    realTemps.push(result);
                })));
                
            })
            .then(() => {
                return realTemps;
            })
            
    })

有 2 个请求发送到 http://localhost:3000/checkout。其中一个回应了200,另一个没有回馈任何东西。

这是我的网络标签:

成功响应

没有回报?

如何checkoutserviceNgOnInit方法中获取代码以实际执行?

标签: javascriptnode.jsangularmean-stack

解决方案


推荐阅读