javascript – 从promise Angular 2中设置类的全局变量
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 从promise Angular 2中设置类的全局变量,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2315字,纯文字阅读大概需要4分钟。
内容图文
我在从一个可观察的内部分配对一个类的全局变量的响应时遇到了一个奇怪的问题.所以我的程序逻辑如下:
>从弹性搜索中获取最新的播放列表ID(我使用类型定义文件中的弹性搜索).这将返回一个PromiseLike,我挂钩一个then运算符.
>在承诺解决方案内,我再次进行http get调用(即可观察)
>在Observable订阅中,我为我的全局数组分配来自服务器的响应.
代码工作正常,我得到的答案应该是,但我不能将变量分配给全局变量.
这是我的代码:
import {Component, OnInit} from '@angular/core';
import {PlaylistService} from '../api/services'
@Component({
selector: 'app-playlists',
templateUrl: './playlists.component.html',
styleUrls: ['./playlists.component.css']
})
export class PlaylistsComponent implements OnInit {
public playlists: any[] = [];
constructor(private playlistService: PlaylistService) {
}
ngOnInit() {
let that = this;
this.playlistService.listIds().then((val) => { // <-- promise resolution
return this.playlistService.getByIds(val).toPromise(); // <-- http get call which i then convert to promise for simplicity
}).then((res) => { // <-- resolution of the http get call
console.log(this.playlists); <-- in this log, i get my desired results
// here is my problem, this assignment doesn't happens
this.playlists = res.data;
});
}
}
listIds函数如下:
listIds() {
return this.api.listing('playlist').then((body) => {
let hits = body.hits.hits;
return _.keys(_.groupBy(hits, '_id'));
});
}
这是我的api.listing功能(弹性搜索客户端)
listing(type: string) {
let es = this.prepareES();
return es.search({
index: 'test',
_source: ["_id"],
type: type
});
}
es.search的返回类型是
search(params: SearchParams): PromiseLike>;
任何想法为什么我无法为全局变量赋值?
解决方法:
看起来this.playlistservice.listIds()返回的promise不会在Angulars区域内运行.这就是为什么Angular2不会运行更改检测并且无法识别更改的原因.
您可以在更改后显式调用更改检测:
constructor(private playlistService: PlaylistService, private cdRef:ChangeDetectorRef) {
…
ngOnInit() {
let that = this;
this.playlistService.listIds().then((val) => { // <-- promise resolution
return this.playlistService.getByIds(val).toPromise(); // <-- http get call which i then convert to promise for simplicity
}).then((res) => { // <-- resolution of the http get call
console.log(this.playlists); <-- in this log, i get my desired results
// here is my problem, this assignment doesn't happens
this.playlists = res.data;
this.cdRef.detectChanges();
});
}
内容总结
以上是互联网集市为您收集整理的javascript – 从promise Angular 2中设置类的全局变量全部内容,希望文章能够帮你解决javascript – 从promise Angular 2中设置类的全局变量所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。