我正在使用Angular 2,我试图从用户ID显示用户昵称。当我从dashboard.component.html调用函数getUserName(userId)时,它会调用auth0服务来获取用户配置文件。因此,我收到连续响应,并且无法显示用户昵称。请找到以下代码:
dashboard.component.ts
import { Component} from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Auth0Service } from '../../services/auth0/auth0.service';
@Component({
moduleId: module.id,
selector: 'dashboard',
templateUrl: 'dashboard.component.html'
})
export class DashboardComponent {
constructor(private authService: AuthService, private _auth0Service: Auth0Service){
}
getUserName(userId:string){
let userName:string;
this._auth0Service.getUser(userId)
.subscribe(user=>{
userName=user.nickname;
});
}
return userName;
}
dashboard.component.html
<h1>User Dashboard</h1>
{{getUserName(authService.userProfile.user_id)}}
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());
}
}
app.module.ts
@NgModule({
imports: [ BrowserModule, Routing, HttpModule, ... ],
bootstrap: [ AppComponent ],
providers: [ AUTH_PROVIDERS, AuthService, Auth0Service, AuthGuard, ... ]
})
export class AppModule { }
请注意我想从HTML调用该函数,因为我想在我的评论部分中使用此函数,其中userIds将是不同的!我必须将每个Id传递给函数并获得结果。等待你最早的帮助!!!
由于 阿巴斯
答案 0 :(得分:0)
由于HTTP调用是异步的,因此在获得响应之前返回enum NoteListType {
case tag
case album
}
。这应该这样做:
userName
答案 1 :(得分:0)
请从组件中调用方法getUserName(userId)。您可以在组件的onInit上调用该函数。 例如:
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Auth0Service } from '../../services/auth0/auth0.service';
@Component({
moduleId: module.id,
selector: 'dashboard',
templateUrl: 'dashboard.component.html'
})
export class DashboardComponent implements OnInit{
constructor(private authService: AuthService, private _auth0Service: Auth0Service){}
userName:string="";
ngOnInit(){
this.getUserName(this.authService.userProfile.user_id);
}
getUserName(userId:string){
let userName:string;
this._auth0Service.getUser(userId)
.subscribe(user=>{
this.userName=user.nickname;
});
}
}
}
并在你的HTML中
<h1>User Dashboard</h1>
{{userName}}
答案 2 :(得分:0)
您可以在组件的onInit上调用该函数。例如,请参阅以下代码
import { OnInit} from '@angular/core';
export class DashboardComponent implements OnInit{
let Userid:string;
constructor(private authService: AuthService){
Userid=this.authService.userProfile.user_id;
}
ngOnInit(){
this.getUserName(this.Userid);
}
getUserName(userId:string){
let userName:string;
this._auth0Service.getUser(userId)
.subscribe(user=>{
userName=user.nickname;
});
}
return userName;
}
}