如何使 BehaviorSubject<string> 函数 next() 同时发出字符串的所有字符?
How to make BehaviorSubject<string> function next() emit all character of string at the same time?
我已经这样定义了 BehaviorSubject 和映射值:
const foo$: BehaviorSubject<string> = new BehaviorSubject("asd");
const queryObservable = foo$.pipe(
switchMap(x => {
return x;
}
)
);
queryObservable.subscribe(x => {
console.log(x);
});
在控制台中打印:
a
s
d
但我希望它是:
asd
我做错了什么?
我不知道你想用switchMap
和你写的代码实现什么。
只是为了回答问题,您可以使用 map
而不是 switchMap
const foo$: BehaviorSubject<string> = new BehaviorSubject("asd");
const queryObservable = foo$.pipe(
map(x => {
return x;
}
)
);
queryObservable.subscribe(x => {
console.log(x); // result should be "asd"
});
或
一个简单的方法是,
const foo$: BehaviorSubject<string> = new BehaviorSubject("asd");
foo$.subscribe(x => {
console.log(x);
});
或
与 SwitchMap
,使用 of
运算符
const foo$: BehaviorSubject<string> = new BehaviorSubject("asd");
const queryObservable = foo$.pipe(
switchMap(x => {
return of(x);
}
)
);
queryObservable.subscribe(x => {
console.log(x);
});
我已经这样定义了 BehaviorSubject 和映射值:
const foo$: BehaviorSubject<string> = new BehaviorSubject("asd");
const queryObservable = foo$.pipe(
switchMap(x => {
return x;
}
)
);
queryObservable.subscribe(x => {
console.log(x);
});
在控制台中打印:
a
s
d
但我希望它是:
asd
我做错了什么?
我不知道你想用switchMap
和你写的代码实现什么。
只是为了回答问题,您可以使用 map
而不是 switchMap
const foo$: BehaviorSubject<string> = new BehaviorSubject("asd");
const queryObservable = foo$.pipe(
map(x => {
return x;
}
)
);
queryObservable.subscribe(x => {
console.log(x); // result should be "asd"
});
或
一个简单的方法是,
const foo$: BehaviorSubject<string> = new BehaviorSubject("asd");
foo$.subscribe(x => {
console.log(x);
});
或
与 SwitchMap
,使用 of
运算符
const foo$: BehaviorSubject<string> = new BehaviorSubject("asd");
const queryObservable = foo$.pipe(
switchMap(x => {
return of(x);
}
)
);
queryObservable.subscribe(x => {
console.log(x);
});