angular - 服务中保存的数据在页面刷新或更改时丢失

标签 angular angular-services google-oauth

我有一个 Angular 5 应用程序,我正在尝试使用 Google OAuth 登录来获取用户名,然后在服务中设置该用户名以用作登录用户。在添加登录名之前,我在服务中手动设置了该值,并且没有问题。现在我从谷歌登录设置用户名,每次页面刷新(或调用服务的新实例时)我设置的值似乎都会丢失。

该值从 Google 登录正确返回(我在控制台中检查),所以我知道那里一切正常。我对 Angular 服务的印象是它们在其他模块中是不变的?是不是每次我调用该服务时都会创建一个新的空“tempuser”变量?如果是这样,有什么办法可以解决这个问题,以便我可以在整个应用程序中保留该值,直到用户注销?

这是服务本身:

import { Injectable } from '@angular/core';
import { Http, Response, Headers } from "@angular/http";

@Injectable()
export class WmApiService {

  //private _baseUrl = "http://wm-api.webdevelopwolf.com/"; // Test server api
  private _baseUrl = "http://localhost:58061/"; // Dev server api 
  tempuser = "";
  tempuseravatar = "";
  tempuserfullname = "";
  tempuseremail = "";
  userloggedin = 0;
  modules: any;

  constructor(private _http: Http) {
    console.log('Wavemaker API Initialized...');
  }

  // On successful API call
  private extractData(res: Response) {
    let body = res.json();
    return body || {};
  }

  // On Error in API Call
  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }

  // Basic Get W/ No Body
  getService(url: string): Promise<any> {
    return this._http
        .get(this._baseUrl + url)
        .toPromise()
        .then(this.extractData)
        .catch(this.handleError);
  }

  // Basic Post W/ Body
  postService(url: string, body: any): Promise<any> {
    console.log(body);
    let headers = new Headers({'Content-Type': 'application/json'});
    return this._http
      .post(this._baseUrl + url, body, {headers: headers})
      .toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }

}

还有一个简单的例子来说明它的名字:
import { Component, OnInit } from '@angular/core';
import { WmApiService } from '../../wm-api.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  userSignedToJourney: boolean;

  constructor(private _wmapi: WmApiService) { }

  ngOnInit() {
    this.userRegisteredToJourney();
  }

  // Check if Trailblazer is already on Journey
  userRegisteredToJourney() {
    this._wmapi
    .getService("Journey/TrailblazerRegistered/" + this._wmapi.tempuser)
    .then((result) => {
      if (result == 1) this.userSignedToJourney = true; else this.userSignedToJourney = false;
    })
    .catch(error => console.log(error));
  }

}

临时用户值设置如下:
import { Component, OnInit } from '@angular/core';
import { WmApiService } from '../wm-api.service';
import { Router } from "@angular/router";

declare const gapi: any;

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})

export class LoginComponent implements OnInit {

  constructor(private _wmapi: WmApiService, private router: Router) { }

  public auth2: any;
  userProfile: any;
  user: any;

  // Initalise Google Sign-On
  // NOTE: Currently registered to http://localhost:4200/ - will need to change when on server to final URL
  public googleInit() {
    gapi.load('auth2', () => {
      this.auth2 = gapi.auth2.init({
        client_id: '933803013928-4vvjqtql0nt7ve5upak2u5fhpa636ma0.apps.googleusercontent.com',
        cookiepolicy: 'single_host_origin',
        scope: 'profile email',
        prompt: 'select_account consent'
      });
      this.attachSignin(document.getElementById('googleBtn'));
    });
  }

  // Log user in via Google OAuth 2
  public attachSignin(element) {
    this.auth2.attachClickHandler(element, {},
      (googleUser) => {
        // Get profile from Google
        let profile = googleUser.getBasicProfile();        
        // Save user to the API until changed
        this._wmapi.tempuser = profile.getName().match(/\(([^)]+)\)/)[1];
        this._wmapi.tempuseravatar = profile.getImageUrl();
        this._wmapi.tempuserfullname = profile.getName();
        this._wmapi.tempuseremail = profile.getEmail();
        // Log the user in
        this._wmapi.userloggedin = 1;
        // Redirect to dashboard
        this.router.navigate(['/dashboard']);
      }, (error) => {
        alert(JSON.stringify(error, undefined, 2));
        // To get auth token - googleUser.getAuthResponse().id_token;
        // To get user id - profile.getId();
      });
  }

  ngAfterViewInit(){
    this.googleInit();
  }

  ngOnInit() {
  }

}

最佳答案

这里有些事情看起来不正常。

  • 依赖注入(inject)错误

  • 您将 WM API 服务注入(inject)到组件中,然后在那里进行配置。这不应该是这种情况,您应该在服务本身和 init 上执行此操作。并且该服务在获取此 google API 数据之前不应处于“就绪”状态。一方面,你的组件不应该关心配置服务——它只是请求服务并使用它们。其次,如果您在其他地方使用服务,例如当没有登录组件时,谁来配置您的服务?第三,如果您有多个服务实例,这可能意味着您做错了 - 您应该在全局应用程序级别提供服务,以便它们都使用相同的实例,但即使没有,您仍然需要拥有服务照顾它的依赖关系,而不是服务消费者。

    修复此特定部分的步骤:
  • 从组件中取出 gapi.load() 等内容并将其放入服务中
  • 在应用程序级别提供服务,而不是在组件(或惰性模块)级别,如果可能的话。
  • 页面重新加载问题

  • 可能其中一些东西是持久的 - 你说在页面重新加载时,你会丢失一些东西。这是合乎逻辑的 - 在每次重新加载页面时,内存中的内容都会消失,并且您拥有一个全新的应用程序。也许您想存储 JWT token 之类的东西并将其访问到 sessionStoragelocalStorage 中。如果有这样的东西需要在页面重新加载中持续存在,您还应该在您的应用程序中构建并提供一个存储服务,为您的 WM API 服务(和其他)提供序列化/反序列化服务。同样,WM Api 服务被注入(inject)了这个存储,所以它可以在启动时配置自己(在它的构造函数中)。
  • Http错误
  • Http , Headers , Response 基本上整个 @angular/http 在 Angular 4.3 中被弃用 - 你应该使用 HttpClient 和来自 @angular/common/http 的 friend 。改变应该非常简单,而且值得。
    另外,试着让自己脱离 Http 客户端上的 .toPromise() 并进入 observables。它将使在整个应用程序中更容易处理其他事物(也是可观察对象),并且更改也相对较小 - Http(Client) 可观察对象在成功或失败后无论如何都会完成,因此您的逻辑应该仍然相同(只需使用 subscribe(successHandler, errHandler) 代替then(successHandler, errHandler) )。
  • 文档

  • 我看到你也在使用 document.getElementById (可能还有其他东西)。你最好不要直接使用浏览器全局变量,而是注入(inject) Angular 提供的代理。从长远来看,你会感谢自己做了这件事。

    关于angular - 服务中保存的数据在页面刷新或更改时丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53006568/

    相关文章:

    unit-testing - 在 Angular 2.1.0 Webpack 上设置单元测试代码覆盖率

    angular - inject() 必须从注入(inject)上下文中调用

    Angular::error TS2532:对象可能是 'undefined'

    android - android中的谷歌登录授权错误

    python - 如何刷新存储的 Google oAuth 凭据

    angular - 禁用 Angular 2+ html 模板中的绿色波浪线

    javascript - 如何替换因丢失或错误图像 src 而损坏的 HTML img

    javascript - 如何在 AngularJS 中正确注入(inject)模块

    google-oauth - Google Apps OAuth2 身份验证在许多安装中突然停止工作 ("policy_enforced"错误)