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