简体   繁体   English

Angular / Typescript - 无法更新订阅中的外部变量 function

[英]Angular / Typescript - Could not update outside variable in the subscribe function

below is my code, I just want to query the backend if email already registered or not, however, no matter what email I pass to the verifyEmail function, the "registered" variable always false, how can I update the registered variable according to the backend response?下面是我的代码,我只想查询后端 email 是否已经注册,但是,无论 email 我传递给 verifyEmail ZC1C425268E68385D1AB5074C17A94F14 的变量如何,我总是可以更新注册变量为“false”如何,后端响应? Thanks谢谢

export class MyClass {

   registered: boolean = false;
   message: string = ''

   verifyEmail(email) { 
        this.registered= false
        
        let verifyEmailUrl = "/backend/GetUserByEmail";
        this.http.post(verifyEmailUrl, {
            email: email
        }).subscribe(
            (data) => {
                if (data["user"]) { // can find a user
                    this.message = 'This email has already been registered'
                    this.registered= true
                }
            });
}

You are using an arrow function, your scope should be shared and this.registered should be updated appropriately.您正在使用箭头 function,您的 scope 应该被共享并且this.registered应该被适当地更新。 Please provide a console.log of data or more relevant code.请提供console.log数据或更相关的代码。 The issue does not appear to be identifiable from your question.该问题似乎无法从您的问题中识别出来。

How do you check registered value?你如何检查注册价值? You can't get this value immediately after verifyEmail execution, because value will update some time later.您无法在执行 verifyEmail 后立即获取此值,因为值会在一段时间后更新。 You can create BehaviorSubject then subscribe on it and get register value anywhere when it will update您可以创建 BehaviorSubject 然后订阅它并在它更新时在任何地方获取注册值

export class MyClass {

   registered$ = new BehaviorSubject<boolean>();
   message: string = ''

   verifyEmail(email) {             
        let verifyEmailUrl = "/backend/GetUserByEmail";
        this.http.post(verifyEmailUrl, {
            email: email
        }).subscribe(
            (data) => {
                if (data["user"]) { // can find a user
                    this.message = 'This email has already been registered'
                    this.registered$.next(true)
                } else {
                    this.registered$.next(false)
                }

            });
}

In outer code:在外部代码中:

myClassObject.registered$.asObservable().subscribe(registered => console.log(registered));

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

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