首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Vuex模块中使用RxJS

如何在Vuex模块中使用RxJS
EN

Stack Overflow用户
提问于 2019-08-17 21:31:03
回答 2查看 2K关注 0票数 3

我创建了一个由auth服务使用的API服务,该服务由Vuex模块使用。在我的登录组件中,我使用Vuex模块与API通信,但是调用不等待API响应。

API服务:

代码语言:javascript
复制
class ApiService {
  protected readonly api = 'https://xxx.yzz:44310/api'
  private static instance: ApiService
  private headers = {
    'Content-Type': 'application/json'
  }

  constructor() {
    this.init()
  }

  private init() {
    Vue.use(VueAxios, axios)
    Vue.axios.defaults.baseURL = this.api
  }

  public static get Instance() {
    return this.instance || (this.instance = new this())
  }

  private handleError(error: any) {
    const applicationError = error.headers['Application-Error']
    return Observable.throw(modelStateErrors || 'Server error')
  }

  get(path: string, params: URLSearchParams = new URLSearchParams()):     Observable<any> {
    return from(axios.get(`${path}`, { params })).pipe(catchError(this.handleError))
  }

  put(path: string, body: Object = {}): Observable<any> {
    return from(axios.put(`${path}`,     JSON.stringify(body))).pipe(catchError(this.handleError))
  }

  post(path: string, body: Object = {}): Observable<any> {
    return from(
      axios.post(`${path}`, JSON.stringify(body), {
        headers: this.headers
      })
    ).pipe(catchError(this.handleError))
  }



export const apiService = ApiService.Instance

授权服务:

代码语言:javascript
复制
class AuthService {
  private static instance: AuthService

  private constructor() {}

  public static get Instance() {
    return this.instance || (this.instance = new this())
  }

  public login(credentials: Credentials): Observable<any> {
    return apiService.post('/auth/login', credentials).pipe(map(result => result.data))
  }
}

export const authService = AuthService.Instance

Vuex模块具有授权方法:

代码语言:javascript
复制
import { Module, VuexModule, Mutation, Action } from 'vuex-module-decorators'
import { Credentials } from '@/core/models/credentials.interface'
import { authService } from '@/core/services/auth.service'
import { Usuario } from '@/core/models/usuario.interface'

@Module
export default class Auth extends VuexModule {
  count = 0
  usuario: Usuario | null = null
  isAuthenticated: boolean = false

  @Mutation
  setUsuario(usuario: Usuario) {
    this.usuario = usuario
    this.isAuthenticated = true
  }

  @Action({})
  public authRequest(credentials: Credentials) {
    return authService.login(credentials).subscribe(
      (usuario: Usuario) => {
        this.context.commit('setUsuario', usuario)
      },
      (errors: any) => {
        console.log('errors', JSON.stringify(errors))
      }
    )
  }
}

在我的登录组件中,我使用Vuex模块如下:

代码语言:javascript
复制
  onSubmit() {
    (this.$refs.userCredentials as any).validate((valid: boolean) => {
      if (valid) {
        this.$store
          .dispatch('authRequest', this.userCredentials)
          .then(() => {
            this.$router.push('/');
          })
          .catch((err) => {
            console.error(err);
          });
      } else {
        console.log('error submit!!');
        return false;
      }
    });
  }

我期望的结果是,当我按下登录按钮时,代码将等待API响应,并根据结果采取接下来的步骤。

EN

回答 2

Stack Overflow用户

发布于 2019-08-18 04:02:23

authRequest正在返回一个Subscription,但是为了使用.thenonSubmit逻辑在这里需要一个Promise类型。您可能希望在.tap/.do后面加上authRequest中的.toPromise

票数 0
EN

Stack Overflow用户

发布于 2019-08-30 11:24:45

是的,你在行动中返回订阅,这是你不想做的。在操作中将.subscribe替换为.pipe(shareReplay())。可观察实现PromiseLike,因此您可能对此没有意见。如果这仍然不起作用,则必须在操作中返回语句的末尾调用.toPromise()。一个vuex-rxjs图书馆将是一件美好的事情,我希望我有时间去做它。希望其他人很快就会:)

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57540079

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档