简体   繁体   English

如何等待订阅完成 pipe 和 map

[英]How to wait for subscribe to finish with pipe and map

In my backend - express.js I am successfully returning a boolean value which tells me if a user exists or not.在我的后端 - express.js 中,我成功返回了一个 boolean 值,它告诉我用户是否存在。

Problem is in my frontend - angular(newest version), when I receive that value, I need to use that value right after asynchronous execution.问题出在我的前端 - 角度(最新版本),当我收到该值时,我需要在异步执行后立即使用该值。

So I decided to use RxJS pipe + map所以我决定使用 RxJS pipe + map

I get this:我明白了:

Argument of type 'Observable<unknown>' is not assignable to parameter of type 'OperatorFunction<boolean, unknown>'.
  Type 'Observable<unknown>' provides no match for the signature '(source: Observable<boolean>): Observable<unknown>'.ts(2345)
The 'this' context of type 'void' is not assignable to method's 'this' of type 'Observable<unknown>'.

ApiService.ts APIService.ts

checkIfUserExists(email: string): Observable<boolean> {
    return this.http.get<boolean>(`${this.COINS_URL}/login/check/${email}`);
  }

register.component.ts注册组件.ts

let value = null
        this.apiService.checkIfUserExists(this.user.email)
  .pipe(
    map(data => console.log(data))
  )
    console.log(value) -- returns [object Object]

How do I resolve this issue and use pipe + map successfully?如何解决此问题并成功使用 pipe + map?

Edit for comments:编辑评论:

checkIfUserExists() {
    this.user = this.userRegistrationForm.value
    return this.apiService.checkIfUserExists(this.user.email)
      .pipe(
        map(data => data))
      .subscribe(e => e.userExists)
  }

When trying to use - I get [object Object]尝试使用时 - 我得到 [object Object]

userExists = this.checkIfUserExists()
    console.log('userExists: ' + userExists)

Edit 2: Final solution, thanks for all the help Problem was solved using callbacks Big thanks to this post: How do I return the response from an asynchronous call?编辑 2:最终解决方案,感谢所有帮助 使用回调解决了问题 非常感谢这篇文章: 如何从异步调用返回响应?

Code:代码:

checkIfUserExists(callback) {
    this.user = this.userRegistrationForm.value
    console.log("2. callback here is the function passed as argument above...")
    this.apiService.checkIfUserExists(this.user.email)
      .pipe(
        map(data => data))
      .subscribe(e => {
        console.log("3. start async operation...")
        console.log("4. finished async operation, calling the callback, passing the result...")
        callback(e.userExists)
      })
  }

onSubmit() {
    let userExists = null
    console.log("1. function called...")
    this.checkIfUserExists((result: boolean) => {
      // 5. Received the result from the async function,
      //    now do whatever you want with it:
      console.log("5. result is: ", result);
      userExists = result
      this.userExistsValidator(userExists)
  });
  }

You need to return from.pipe(map), like below.您需要从.pipe(map) 返回,如下所示。 This will cause function to wait for service to get the response and then return the value.这将导致 function 等待服务获得响应然后返回值。 So doing this will not return null value or return from function before service has get any response.因此,在服务获得任何响应之前,这样做不会返回 null 值或从 function 返回。

let value = null
        return this.apiService.checkIfUserExists(this.user.email)
  .pipe(
    map(data =>{
    console.log(data);    
    return data; 
    })
  );

Take a look at the signature of map from the documentation.从文档中map的签名。 You will need to return an observable.您将需要返回一个 observable。 Signature:签名:

map(project: Function, thisArg: any): Observable

Now make the following change:现在进行以下更改:

checkIfUserExists() { 
   return this.apiService.checkIfUserExists(this.user.email)
    .pipe(
      map(data => data)  // needed only if you need projection
      })
    );
}

Points to note:注意事项:

  1. Omit the {} and return when there is just one statement within the map operator.map运算符中只有一条语句时,省略{}return
  2. In this case, I don't think you need the map operator unless you are trying to project certain properties from the observable.在这种情况下,我认为您不需要map运算符,除非您尝试从 observable投影某些属性。
  3. Unless you subscribe to an observable, it will not emit the values from it.除非您订阅一个可观察对象,否则它不会从中发出值。

Invoke it using: (since it is asynchronous)调用它使用:(因为它是异步的)

this.checkIfUserExists().subscribe(e => userExists = e);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM