`Unceasing Replies Generated by the Function in Angular 2`

I am currently working with Angular 2 and facing an issue in displaying the user-nickname based on the User ID.

Whenever I invoke the getUserName(userId) function from comments.component.html, it triggers the auth0 service to retrieve the user profile. However, I'm encountering a stream of responses and struggling to showcase the user-nickname. The console.log(user) seems to generate an endless response! The Comments Component is embedded within feeds.component.html. Since each ID may vary, I have to call the function repeatedly.

Snippet of the code can be found below:

comments.component.html

<ul class="list-group" *ngIf="commentsArray.length>0">
  <li class="list-group-item" *ngFor="let comment of commentsArray; let i = index">
    {{getUserName(comment.comment_by)}}: {{comment.comment_text}}
  </li>
</ul>

comments.component.ts

import { Component, Input, OnInit } from '@angular/core';
import { FeedsService } from '../../services/feeds/feeds.service';
import { AuthService } from '../../services/auth.service';
import { Auth0Service } from '../../services/auth0/auth0.service';

@Component({
moduleId: module.id,
selector: 'comments',
templateUrl: 'comments.component.html',
providers: [FeedsService]
})

export class CommentsComponent implements OnInit {
@Input() commentsType:string;
@Input() editId:string;
@Input() data:any;

constructor(private authService: AuthService, private _feedsService: FeedsService, private _auth0Service: Auth0Service){
}

ngOnInit(){
    this.commentsArray=this.data.comments;
}

getUserName(userId:string){
    let userName:string;
    this._auth0Service.getUser(userId)
        .subscribe(user=>{
            console.log(user);
            userName=user.nickname;
        });
    return userName;
    }
}

auth0.service.ts

import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions} from '@angular/http';
import { AuthHttp } from 'angular2-jwt';
import 'rxjs/add/operator/map';

@Injectable()
export class Auth0Service {

constructor(private _http:Http, private _authHttp: AuthHttp) {
}

getUser(userId: string){
    let headers = new Headers({'Content-Type': 'application/json'}); 
    headers.append('Authorization', 'Bearer token');
    let options = new RequestOptions({headers: headers});
    return this._http.get('https://url.auth0.com/api/v2/users/'+userId, options)
    .map(res => res.json());
    }
}

feeds.component.html

<div class="col-sm-12 feed-container" *ngFor="let feed of feeds; let i = index">
    <comments [commentsType]="commentsType" [editId]="feed._id" [data]="feed">
    </comments>
</div>

app.module.ts

@NgModule({
  imports:      [ BrowserModule, Routing, HttpModule, ... ],
  bootstrap:    [ AppComponent ],
  providers:    [ AUTH_PROVIDERS, AuthService, Auth0Service, AuthGuard, ... ]
})
export class AppModule { }

Your earliest assistance is greatly appreciated.

Abbas

Answer №1

It is not possible to simply return a value from an asynchronous call

getUserName(userId:string){
    let userName:string;
    this._auth0Service.getUser(userId)
        .subscribe(user=>{
            console.log(user);
            userName=user.nickname;
    });
    // At the time of execution of this line, `userName` does not have a value yet
    return userName;
}

Instead, you can return an observable like this:

prevUserId:string;
prevObservable;

getUserName(userId:string){
  if(this.prevUserId === userId) {
    return this.prevObservable;
  }
  this.prevUserId = userId;
  this.prevObservable = this._auth0Service.getUser(userId)
      .map(user=>{
          console.log(user);
          return user.nickname;
       });
  return this.prevObservable;
}

And then display the value using:

{{getUserName(comment.comment_by) | async}}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Material Angular table fails to sort columns with object values

Currently, I am in the process of developing a web application using Angular Material. One of the challenges I have encountered is displaying a table with sorting functionality. While sorting works perfectly fine on all columns except one specific column. ...

Can errors be selectively ignored in Angular's global error handler based on certain conditions?

I am currently facing a situation where I need to handle errors when calling an API to save data, either manually or automatically. For manual saves, I have implemented an Angular global error handler to display the error message if the save fails. Howeve ...

Tips on Importing a Javascript Module from an external javascript file into an <script> tag within an HTML file

I'm facing an issue while attempting to import the 'JSZip' module from an external node package called JSZip in my HTML File. The usual method of importing it directly using the import command is not working: <script> import ...

Image cannot be shown due to unknown URL scheme in Angular

I am currently working on an Angular application and I am facing an issue with displaying images on my website. When I check the console, I see the following error messages: unsafe:url(http://local.api.test.come/Uploads/af21cb1b-066c-48c6-b6d6-0116a133810 ...

What steps can be taken to disable auto correction in ngx date picker?

In my application, I am utilizing ngx-datepicker with 'DD.MM.YYYY' as the dateInputFormat in the configuration settings of the date picker. The challenge arises when I manually input a date following the format 'YYYY.MM.DD', as the ente ...

Angular and TypeScript make a powerful combination when working with the mat-table component

I'm currently working with Angular's mat-table component. One challenge I'm facing is setting a caption for the table. <table mat-table [dataSource]="dataSource" class="mat-elevation-z8" id=tbl_suchergebnis> <caption> ...

`"Type is invalid" error occurring with component after importing it into a different project``

I am currently working on developing a custom Storybook 7 Typescript component library with React. I have successfully imported this library into another project using a private NPM package. However, one of the components in the library, specifically the ...

Retrieve information from a JSON response that is in comma-separated format and adjust the button to be either enabled or disabled depending on the value in IONIC

I received a JSON response with one parameter containing a comma-separated string as shown below: this.dataList = [{ "id":1, "name": "Ram", "total_slots": 3, "alloted_slot":"a1,a2,a3" }, { "id":2, "name": "As ...

Angular styling for input elements that are in the pristine state

Hey there, I'm working with a CSS class that applies a red border to an input field when it is required and invalid, and changes to green when it becomes valid. CSS .ng-valid[required], .ng-valid.required { border-left: 5px solid #42A948; /* green ...

Contrasting the Appmodule and Pages module within Angular: A Comparison

After cloning this project, I noticed that it contains two types of modules: one inside the page and the other in the root directory. Directory Tree: https://i.sstatic.net/tjq0I.png App.module.ts import { BrowserModule } from '@angular/platform-bro ...

What is the best approach to manage dynamic regex values for input types within ngFor loop?

In my project, I have an array of objects containing details for dynamically generating input fields. I have successfully implemented the dynamic input field generation based on the type received from an API. However, I am facing a challenge with matching ...

Step-by-step guide to creating a flip effect with Angular 2 animations

I've been utilizing pure css flip of cards in my project, but I feel like it's not the best solution. Does anyone know how to create a card flip in angular 2 upon clicking a button? I came across one in angularjs here <div ng-app="cardFli ...

Using Typescript to define property types based on their respective values

Is it possible to set a property type based on the property value? For example, if the command is: If 'set' then the payload must be PayloadSet If 'put' then the payload must be PayloadPut If 'del' then the payload must be ...

Avoiding page reload when utilizing the nebular menu-bar item's 'url' attribute

I have implemented the nebular theme in my application, with a menu containing two items that can be navigated using the URL attribute of the nebular menu. ISSUE: While the navigation works correctly, a page refresh occurs every time an item is clicked. ...

The karma test-runner is throwing an error code TS2503, indicating that the namespace 'gapi' cannot be located

karma test-runner error TS2503: Cannot find namespace 'gapi' ng test Trace 28 01 2021 14:50:25.878:INFO [karma-server]: Karma v5.2.3 server started at http://localhost:9876/ 28 01 2021 14:50:25.878:INFO [launcher]: Launching browsers Firefox wit ...

Can an IonChange event be triggered from a component in Ionic 3?

Currently, I am working on developing an application that involves multiple forms. In most instances, when a user navigates back from the Confirmation view to the Form view to modify their entered data, it is essential for the form to retain the previously ...

Version 5 of angularfie2 is encountering an issue where the type 'Observable<{}[]>' cannot be assigned to the type 'Observable<any[]>'

Encountering an error while using angularfire2 version 5: The error reads: "Type 'Observable<{}[]>' is not assignable to type Observable < any [] >." Code snippet: exercisesList$: Observable <any[]>; ionViewDidLoad() { ...

Is there a way to access FormArray within a formGroup nested inside another formGroup?

I have a set of data structured like this: [ { id: "1", name: "task1", taskForms: [ { id: "8782", name: "ProcedureComment", sortOrder: null, descr ...

Pause the execution at specific points within Typescript files by utilizing breakpoints when debugging with an attached debugger in VsCode

My current challenge involves setting up a debugger in VsCode with the attach mode on a Typescript codebase running in a Docker container. Despite successfully attaching the debugger in VsCode and hitting breakpoints, I consistently find myself landing on ...

Trigger functions on a universal component from the nested component

I am currently working on an Angular project with two components, one being a generic component where the table is defined and the other being a component that invokes this table by passing the required data. However, I encountered an issue where the tabl ...