I'm creating an Angular app that's based on Youtube Data API. I need to use OAuth to let users sign-in in order to access their data. The current problem is that, during the development process, the user's sign-in state will change back to false once I refresh the page, which is clearly not what I wanted. I'm kinda confused about how to keep users logged in here. Hope someone can help me out.
Here is my TS code for handling user sign-in:
GoogleAuth: any;user: any;isAuthorized = false; ngOnInit(): void { // Load auth2 library gapi.load("client:auth2", this.initClient); } loadClient = () => { gapi.client.setApiKey(this.API_KEY); return gapi.client // same as "https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest" .load("youtube", "v3") .then( () => { console.log("GAPI client loaded for API"); }, function (err) { console.error("Error loading GAPI client for API", err); } ); } // Init API client library and set up sign in listeners initClient = () => { gapi.client .init({ discoveryDocs: this.DISCOVERY_DOCS, clientId: this.CLIENT_ID, scope: this.SCOPES, }) .then(() => { this.GoogleAuth = gapi.auth2.getAuthInstance(); // Listen for sign-in state changes. this.GoogleAuth.isSignedIn.listen(this.handleSigninStatus); // Handle initial sign-in state. (Determine if user is already signed in.) this.handleSigninStatus(); this.loadClient() }); } handleSigninStatus = () => { this.user = this.GoogleAuth.currentUser.get(); this.isAuthorized = this.user.hasGrantedScopes(this.SCOPES); if (this.isAuthorized) { this.loadClient() // this.getChannelInfo() //display playlist data } else { //do nothing } } // Handle login handleAuthClick = () => { this.GoogleAuth.signIn({ scope: this.SCOPES }) .then(() => { console.log("Sign-in successful"); // this.isLoggedIn = true this.getChannelInfo() }, (err: any) => { console.error("Error signing in", { err }) }); } // Handle logout handleSignoutClick = () => { this.GoogleAuth.signOut(); this.GoogleAuth.disconnect(); // gapi.auth2.getAuthInstance().signOut().then(() => { this.googleUser = null }); }This section is where I handle log-in logic in the HTML file, it should display 'Log In' initially and change to 'Log Out' once user signed in.
<mat-toolbar><a href="/">My Application</a><ng-template [ngIf]="isAuthorized" [ngIfElse]="loggedOut"><button mat-raised-button color="warn" id="signout-button" (click)="handleSignoutClick()">Log Out</button></ng-template><ng-template #loggedOut><button mat-raised-button color="warn" id="authorize-button" (click)="handleAuthClick()">Log In</button></ng-template></mat-toolbar>