【发布时间】:2017-03-21 20:44:24
【问题描述】:
我正在使用 Angular 2,我正在尝试从用户 ID 显示用户昵称。
当我从 cmets.component.html 调用函数 getUserName(userId) 时,它会调用 auth0 服务来获取用户配置文件。结果,我收到了持续的回复,并且无法显示用户昵称。 console.log(user),显示永无止境的响应!评论组件嵌套在 feeds.component.html 中。每个 ID 可以不同,因此我必须每次调用该函数。
请在下面找到代码:
cmets.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>
cmets.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 { }
等待您最早的帮助。
阿巴斯
【问题讨论】:
标签: angular typescript angular2-services