有什么方法可以直接return字符串值跟随方法吗?

Are there any way to directly return string value follwing method?

我写了一个函数来存储 'user' 值。但我需要知道,我可以直接获取字符串值并将其分配给变量吗?

我的第二个问题,如果我做不到,如何从 Observable 中获取价值。?目前我将它分配给一个局部变量并在方法中使用。实际上,这种方式是正确的,我需要知道如何删除 return 类型。

readonly id$: Observable<string> = this.store.select(selectUser)
    .pipe(
     mergeMap((currentUser: CurrentUser) => {
        this.localid = currentUser.id; //assign local variable
        return currentUser.id; //retrn value
      }), shareReplayUntil(this.destroySub));

是的,您可以将值赋给函数内的 local/global 变量。

如果我理解得很好,this.store.select 是一个 Observable。这取决于 this.store.select 背后的 Observable 类型,但您可以订阅一个 Observable 来获取值。不需要 pipemergeMap.

示例:

this.store.select(selectUser).subscribe(
  (currentUser: CurrentUser) => { // <-- here you will get the new value
    this.localid = currentUser.id; // <-- and you can assign it
  }
)

使用您的代码:

this.store.select(selectUser)
.pipe(
 mergeMap((currentUser: CurrentUser) => {
    return currentUser.id; //return value to the subscribers
  }), shareReplayUntil(this.destroySub)
).subcribe(id => this.localid = id); // because of the mergeMap we get the id directly

Observable 是异步的,它不会立即 return 一个值。要获得该值,您必须订阅 Observable,Observable 会将新值发送给所有订阅者。