【问题标题】:Access Observable values and assign to a collection访问 Observable 值并分配给集合
【发布时间】:2018-10-23 12:31:01
【问题描述】:

我从 Angular 服务接收到一个 Observable 返回,当它使用 .subscribe 解析时,我可以看到从服务返回的数据

returnedObservable$.subscribe(res => {
    console.log(res);
    return res;
]);

我尝试将其分配给 .subscribe 内的一个对象,但分配没有发生。

let newObj = {};
returnedObservable$.subscribe(res => newObj = res);

我怎样才能进行这项分配以从 Observable 中获取值?

它第一次尝试访问响应时,结果为null,但最终解决了。

console.log(res) 看起来像这样:

{
    itemList: [
        { id: 1, name: Steve },
        { id: 2, name: Bob },
        { id: 3, name: Tim }        
    ]
}

【问题讨论】:

  • 我认为问题在于您正试图在订阅行之后使用 newObj。那是行不通的。 Observables(通常)是异步的。您需要对订阅中的数据in 做任何您想做的事情。
  • 这是有道理的,因为它第一次返回null。到目前为止,我只尝试进行分配,然后尝试打印出对象或数组。我的最终目标是访问该嵌套数组并在 DOM 中使用 ngFor 循环遍历它。你能推荐一种方法吗?
  • 只需将结果分配给 subscribe 内部的类成员,并确保使用 ngIf 保护 ngFor,因为它暂时不会设置(因为它是异步的)。或者,将 observable 本身分配给类成员并使用异步管道。所有这些都包含在 Angular ToH 指南中。
  • `但是任务没有发生。` - 你确定吗?

标签: javascript angular typescript rxjs observable


【解决方案1】:

你可以这样使用它:

let newObj = {};
returnedObservable$.subscribe(res => {newObj = res}).add(()=>
{ 
   //Use your object here
   console.log(newObj);
});

【讨论】:

    猜你喜欢
    • 2017-03-11
    • 2016-11-12
    • 2016-09-10
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2022-06-14
    • 2018-08-30
    • 1970-01-01
    相关资源
    最近更新 更多