return 无法在构造函数内调用服务

return not working in call to service inside a constructor

概览

我正在学习 Angular 和 Jhipster 我需要获取用户名 在控制台中显示它恰到好处但没有真正将值返回到我需要的变量a

这是函数

nombreResponsable(id){

    this.userService.findById(id).subscribe(
        (res: HttpResponse<IUser>) => { 
            console.log(res.body.login);
            return res.body.login;
        },
        (res: HttpErrorResponse) => this.onError(res.message)
    );

}

这是对函数的调用

cargarActividades(id, meta, estrategia, id_meta) {
        this.activiadesDespliegueService.findByEstrategia(id).subscribe(
            (res: HttpResponse<IActividadesDespliegue[]>) => {
                this.actividadesDespliegues = res.body;

                this.actividadesDespliegues.forEach(key => {

                    var responsable = this.nombreResponsable(key.responsableId); 
                    console.log(responsable);
                    //here is where i get null 
                    var datosActividad = {
                        meta: meta,
                        id: key.id,
                        estrategia: estrategia,
                        actividad: key.nombre,
                        fecha: key.fechaCumpliniento,
                        responsable: responsable,
                        puntacion: key.puntacion
                    };
                    this.cargarEvaluaciones(key.id);
                    this.actividadesDespliegueEstrategico.push(datosActividad);

                    this.listaDeMetas[id_meta].puntos = this.listaDeMetas[id_meta].puntos + key.puntacion;
                });
            },
            (res: HttpErrorResponse) => this.onError(res.message)
        );
    }

在控制台中我看到了这个:

 [Log] undefined (x2)
 [Log] admin
 [Log] cordinador

我的想法

就像我说的我正在学习,但我认为它的工作方式与 Ajax 在 javascript 上的工作方式类似,或者它可能不是正确的语法。

问题

备注

试试这个代码

nombreResponsable(id){

let data = this.userService.findById(id).subscribe(
    (res: HttpResponse<IUser>) => { 
        console.log(res.body.login);
        return res.body.login;
    },
    (res: HttpErrorResponse) => this.onError(res.message)
); }         

由于 observables 的异步行为,您得到 undefined

方法nombreResponsable(id)调用时调用this.userService.findById(id)。考虑到它返回一个可观察对象,它肯定是异步的。

因此,在调用时,您最终会在组件代码中得到 undefined

var responsable = this.nombreResponsable(key.responsableId); 
                    console.log(responsable);
                    //here is where i get null 

一个简单的解决方法是订阅组件中 nombreResponsable 方法返回的可观察对象。

Or even better use the async/await syntax. It makes it more readable.

例如:

// mark this method async
async nombreResponsable(id){
    try {
        const res = await this.userService.findById(id).toPromise();
        return res.body.login;
    } catch (e) {
        // error handling
    }
}

然后在你的组件中标记调用方法也异步使用 await:

async cargarActividades(id, meta, estrategia, id_meta) {
        this.activiadesDespliegueService.findByEstrategia(id).subscribe(
            (res: HttpResponse<IActividadesDespliegue[]>) => {
                this.actividadesDespliegues = res.body;

                this.actividadesDespliegues.forEach(key => {
                    // use await to wait for the response and then execute further.
                    var responsable = await this.nombreResponsable(key.responsableId); 
                    console.log(responsable);
                    //here is where i get null 
                    var datosActividad = {
                        meta: meta,
                        id: key.id,
                        estrategia: estrategia,
                        actividad: key.nombre,
                        fecha: key.fechaCumpliniento,
                        responsable: responsable,
                        puntacion: key.puntacion
                    };
                    this.cargarEvaluaciones(key.id);
                    this.actividadesDespliegueEstrategico.push(datosActividad);

                    this.listaDeMetas[id_meta].puntos = this.listaDeMetas[id_meta].puntos + key.puntacion;
                });
            },
            (res: HttpErrorResponse) => this.onError(res.message)
        );
    }