【问题标题】:Getting "undefined" in the first time using http .get() in Angular 2在 Angular 2 中第一次使用 http .get() 获取“未定义”
【发布时间】:2017-07-17 10:52:02
【问题描述】:

我正在尝试从 Angular 中的端点检索数据。 这是服务:

export class VideosService {
result;
constructor(private http: Http, public router: Router) { }

getVideos() {
    this.http.get('http://localhost:3000/videos?sessionId=' + localStorage.getItem('sessionId'))
        .map(response => response.json())
        .subscribe(result => this.result = result);
        localStorage.setItem('videos', this.result);
        console.log(localStorage);
}

除了第一个之外,它每次都有效。第一个我有“未定义”,另一个我得到了实际的对象。

我做错了什么? 谢谢!

【问题讨论】:

标签: angular typescript angular2-services


【解决方案1】:

在您的代码中:

.subscribe(result => this.result = result);
localStorage.setItem('videos', this.result);

代码localStorage.setItem('videos', this.result); 将在之前 .subscribe(result => this.result = result); 执行。

修复

查找异步编程 JavaScript 或简单地说:

.subscribe(result => {this.result = result;   localStorage.setItem('videos', this.result);});

【讨论】:

  • 没错,你也应该复习一下 RxJS Observers,Luis。
猜你喜欢
  • 2017-01-31
  • 1970-01-01
  • 1970-01-01
  • 2017-04-24
  • 2023-04-07
  • 2016-04-03
  • 2017-03-24
  • 1970-01-01
  • 2017-06-14
相关资源
最近更新 更多