Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 将来自订阅的数据应用到列表_Angular_Typescript_Rxjs - Fatal编程技术网

Angular 将来自订阅的数据应用到列表

Angular 将来自订阅的数据应用到列表,angular,typescript,rxjs,Angular,Typescript,Rxjs,目标: 检索输出数据 { age: 4, name: 'Foo' } { age: 7, name: 'Bar' } 然后在名为“PersonList:Person[]=[];”的变量列表中应用输出数据 问题: 关于如何将输出数据应用于变量PersonList,我尝试了不同的解决方案,但失败了 今天我不知道怎么做 Stackblitz: 谢谢大家! import { of } from 'rxjs'; import { distinct } from 'rxjs/operators';

目标:
检索输出数据

 { age: 4, name: 'Foo' }
 { age: 7, name: 'Bar' }
然后在名为“PersonList:Person[]=[];”的变量列表中应用输出数据

问题:
关于如何将输出数据应用于变量PersonList,我尝试了不同的解决方案,但失败了

今天我不知道怎么做

Stackblitz:

谢谢大家!

import { of } from 'rxjs';
import { distinct } from 'rxjs/operators';

interface Person {
   age: number,
   name: string
}

of<Person>(
    { age: 4, name: 'Foo'},
    { age: 7, name: 'Bar'},
    { age: 5, name: 'Foo'},
  ).pipe(
    distinct((p: Person) => p.name),
  )
  .subscribe(x => console.log(x));

// displays:
// { age: 4, name: 'Foo' }
// { age: 7, name: 'Bar' }
从'rxjs'导入{of};
从“rxjs/operators”导入{distinct};
接口人{
年龄:数字,,
名称:string
}
的(
{年龄:4岁,名字:'Foo'},
{年龄:7岁,姓名:'Bar'},
{年龄:5岁,姓名:'Foo'},
).烟斗(
不同((p:Person)=>p.name),
)
.subscribe(x=>console.log(x));
//显示:
//{年龄:4岁,姓名:'Foo'}
//{年龄:7岁,姓名:'Bar'}

我不确定您在这里遗漏了什么,但您只需要将数据放入一个数组中

let personList = []; // initialize array

of<Person>(
    { age: 4, name: 'Foo'},
    { age: 7, name: 'Bar'},
    { age: 5, name: 'Foo'},
  ).pipe(
    distinct((p: Person) => p.name),
  )
  .subscribe(x => personList.push(x)); // add it to the array
让personList=[];//初始化数组
的(
{年龄:4岁,名字:'Foo'},
{年龄:7岁,姓名:'Bar'},
{年龄:5岁,姓名:'Foo'},
).烟斗(
不同((p:Person)=>p.name),
)
.subscribe(x=>personList.push(x));//将其添加到数组中
您可以利用操作员:

import { distinct, toArray } from "rxjs/operators";

let persons: Person[];

of<Person>(
  { age: 4, name: "Foo" },
  { age: 7, name: "Bar" },
  { age: 5, name: "Foo" }
)
  .pipe(
    distinct((p: Person) => p.name),
    toArray()
  )
  .subscribe(x => {
    persons = x;
  });

console.log(persons);
从“rxjs/operators”导入{distinct,toArray};
出租人:人[];
的(
{年龄:4岁,名字:“Foo”},
{年龄:7岁,姓名:“酒吧”},
{年龄:5岁,姓名:“Foo”}
)
.烟斗(
不同((p:Person)=>p.name),
toArray()
)
.订阅(x=>{
人数=x;
});
控制台日志(人);

或者您可以简单地使用Observable:

const persons$: Observable<Person[]> = of<Person>(
  { age: 4, name: "Foo" },
  { age: 7, name: "Bar" },
  { age: 5, name: "Foo" }
)
  .pipe(
    distinct((p: Person) => p.name),
    toArray()
  );
const persons$:可观=of(
{年龄:4岁,名字:“Foo”},
{年龄:7岁,姓名:“酒吧”},
{年龄:5岁,姓名:“Foo”}
)
.烟斗(
不同((p:Person)=>p.name),
toArray()
);