javascript - 将订阅数据的第一项传递给服务
问题描述
我正在开发需要应用以下机制的角度应用程序:
我的视图有 2 个部分(项目列表和选定项目的详细信息)。用户可以单击某个项目,下一个服务会获取该项目的附加数据并在详细视图中显示它们。如果可用,我还想在开始时自动选择第一个项目。
这是我的服务:
@Injectable()
export class ItemService {
private url: string;
private itemSource = new BehaviorSubject<Item>(null);
selectedItem = this.itemSource.asObservable();
constructor(private http: HttpClient) {
this.url = 'http://localhost:8080/api/item';
}
getItems(): Observable<Item[]> {
let observable = this.http.get<Item[]>(this.url)
.map(items => items.map(item => {
return new Item(item);
}));
return observable;
}
selectItem(item: Item) {
return this.http.get<Item>(this.url + '/' + item.id)
.map(item => new Item(item))
.subscribe(t => this.itemSource.next(t));
}
}
在详细组件中,我正在订阅这样的选定项目:
ngOnInit() {
this.itemService.selectedItem.subscribe(item => this.selectedItem = item);
}
以下代码来自我显示项目列表的组件。我还想在订阅数据后设置选定的项目,但我的代码不起作用。我在 html 模板中迭代 items[] 属性并显示数据,但是当我在订阅数据后访问这个数组时,我得到了未定义的结果。你能修复我的代码吗?谢谢!
public items = [];
constructor(private itemService: ItemService) { }
ngOnInit() {
this.itemService.getItems()
.subscribe(
data => this.items = data,
err => console.log(err),
function () {
console.log('selected data', this.items); // this prints undefined
if (this.items && this.items.length) {
this.itemService.selectedItem(this.items[0])
}
});
}
解决方案
您的问题是您complete
在调用subscribe
. 如您所见,您正在为next
和使用箭头函数error
。
当您定义一个新函数时,function(...) {...}
您正在创建一个新上下文,因此this
关键字会改变其含义。箭头函数和普通函数之间的区别(除了更优雅,在我看来)是箭头函数没有为 定义新的上下文this
,因此该关键字的含义与它们定义的上下文相同。因此,在您的next
和error
回调中,this
是您的组件,但在您对 , 的调用中complete
,this
最肯定的是对 的引用window
,它没有items
属性,因此undefined
.
将您的代码更改为:
public items = [];
constructor(private itemService: ItemService) { }
ngOnInit() {
this.itemService.getItems()
.subscribe(
data => this.items = data,
err => console.log(err),
() => {
console.log('selected data', this.items); // this prints undefined
if (this.items && this.items.length) {
this.itemService.selectedItem(this.items[0])
}
});
}
我想你在那里使用了function
关键字,因为该函数没有参数,但你可以用语法来表达() => expression
,或者() => {...}
data => this.items = data
,毕竟是一种更简单更优雅的写法
(data) => { return this.items = data; }
推荐阅读
- c - 检查 revents 到 struct pollfd
- c# - 我可以创建一个循环并监听按键并将此键值获取到 C# 控制台应用程序中的变量而不停止循环吗
- android - Jetpack Compose:仅当 Android 6 设备上的 isAttached 为 true 时,LayoutCoordinate 操作才有效
- django - Django DetailView 和 Update 在同一个表单上相关
- pango - 尝试清理 PangoCairo / FontConfig 时的 SIGABRT
- ember.js - ember data 2.18.x 上的 store.unloadAll 是否假设进行 ajax 调用?
- node.js - ecs.runTask 未在 Lambda 中执行
- mysql - SQL 模式疑问
- cloud-foundry - PCF:创建组织
- javascript - 如何根据兄弟值增加对象值?