我正在使用Angular 2,我正在尝试显示用户ID的用户昵称。
当我从comments.component.html调用函数getUserName(userId)时,它会调用auth0服务来获取用户配置文件。因此,我收到连续响应,并且无法显示用户昵称。 console.log(用户),显示永不停止的响应!注释组件嵌套在feeds.component.html中。每个ID都可以不同,因此我每次都必须调用该函数。
请找到以下代码:
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 { }
等待您的最早帮助。
阿巴斯
答案 0 :(得分:0)
您无法从异步调用中返回值
getUserName(userId:string){
let userName:string;
this._auth0Service.getUser(userId)
.subscribe(user=>{
console.log(user);
userName=user.nickname;
});
// when this line is executed `userName` has no value yet
return userName;
}
您可以返回类似
的可观察对象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;
}
和
之类的值{{getUserName(comment.comment_by) | async}}