【问题标题】:Never Ending Responses from the function in Augular 2Angular 2中函数的永无止境的响应
【发布时间】: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


    【解决方案1】:

    你不能只从异步调用中返回一个值

    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}}
    

    【讨论】:

    • 好吧,没有价值,但为什么响应是连续的???这是主要问题!
    • 如果您在视图中绑定一个方法,如{{getUserName(comment.comment_by)}},则每次更改检测运行时都会调用该方法。如果您更改 getUserName 就像我的答案中显示的那样使用 async 管道像 {{getUserName(comment.comment_by) | async}} 应该修复您的示例。
    • 我试过你的答案... console.log(user) 什么也没显示!其次, auth0.service 已经返回了一个 observable。这就是我使用订阅的原因。最后,我也在我的早期代码中尝试了异步,但我仍然在控制台中获得相同的不间断日志。我尝试了 ChangeDetectionStrategy,它处理连续响应,但随后没有更新我的视图:-(
    • 对不起,你是对的,我忘了加return。 console.log() 外部 map() 或 subscribe() 预计不会打印值。
    • 我说的是这个console.log getUserName(userId:string){ return this._auth0Service.getUser(userId) .map(user=&gt;{ console.log(user); return user.nickname; }); }。这什么都不显示!!!
    猜你喜欢
    • 1970-01-01
    • 2020-06-25
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多