user9515832
user9515832

Reputation:

stay login all of time in application, and when I close the app, restart, shut down mobile etc. using Http in Nativescript

I want to stay login in my app, only when I click log out from system I want to disconnect the connection.

Any idea please?

For login in system I used this code:

export class LoginComponent implements OnInit {
    LoginForm: FormGroup;
    loading: boolean = false;
    constructor(private formBuilder: FormBuilder, private loginservice: LoginService, private router: Router) {
        this.LoginForm = this.formBuilder.group({
            username: ["", Validators.required],
            password: ["", Validators.required]
        });
    }
    public ngOnInit() {
    }

    login() {
            this.loading = true;
            this.loginservice.loginByUsernameAndPassword(
            this.LoginForm.controls['username'].value,
            this.LoginForm.controls['password'].value
        )
            .subscribe(
                result => {
                       if (result === true) {
                        this.router.navigate(['/main']);
                    } else {
                        this.loading = false;
                    }
                }
            );
    }
}

An this code for service.ts

  public loginByUsernameAndPassword(username: string, password: string): Observable<boolean> {
    let urlSearchParams = new URLSearchParams();
    urlSearchParams.append('username', username);
    urlSearchParams.append('password', password);
    let body = urlSearchParams.toString();
    let LS = require("nativescript-localstorage");
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http.post(Api.getUrl(Api.URLS.Login_mobile), body, {
      headers: headers
    })
      .pipe(map((response: Response) => {
        let res = response.json();
        console.log('res')
        console.log(res)
        if (res.StatusCode === 0 && res.Token) {
          this.currentUser = {
            username: username,
            token: res.Token
          }
          LS.getItem(LoginService.CURRENT_USER, JSON.stringify(this.currentUser));
          Toast.makeText('Authentificate successfully').show();
          return true;
        } else {
          return false;
        }
      }));
  }

  public logout(): void {
    let LS = require("nativescript-localstorage");
    LS.removeItem(LoginService.CURRENT_USER);
    this.router.navigate(['/']);
  }

Can you suggest me, any idea how to implement to stay login all of time in application, and when I close the app, restart, shut down mobile etc. I want to disconnect from app only when I click logout.

I'm need your suggestion please.

Upvotes: 1

Views: 98

Answers (0)

Related Questions