【问题标题】:How to fix Error TS2339: Property 'authToken' does not exist on type如何修复错误 TS2339:类型上不存在属性“authToken”
【发布时间】:2020-02-22 16:59:12
【问题描述】:

我正在开发基于 Firabase Realtime DB 的 Ionic 应用程序。尝试启动应用程序时,我收到此错误消息。

[ng] src/app/data-service.service.ts(14,36) 中的错误:错误 TS2339:属性 'authToken' 不存在于类型 '{ apiKey: string; authDomain:字符串;数据库URL:字符串;项目ID:字符串;存储桶:字符串;消息发送者ID:字符串; }'。

Firebase 身份验证似乎有问题。但我不知道如何解决它。

data-service.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment  } from '../environments/environment';
import * as firebase from 'firebase/app';


@Injectable({
  providedIn: 'root'
})
export class DataServiceService {
  userId: any;
  userName: any;
  databaseUrl = environment.firebase.databaseURL;
  authToken = environment.firebase.authToken;

  constructor(private http: HttpClient) {
    console.log('Hello DataServiceService Provider');
    console.log(this.databaseUrl);
    console.log(this.authToken);
    this.userId = localStorage.getItem('userId');
    if (!localStorage.getItem('currentUserShift')) {
      localStorage.setItem('currentUserShift', JSON.stringify({ periods: {} }));
    }
    if (!localStorage.getItem('pendingShifts')) {
      localStorage.setItem('pendingShifts', JSON.stringify([]));
    }
  }

  setUserId(userId) {
    console.log('setUserId ');
    this.userId = userId;
    localStorage.setItem('userId', userId);
  }

  getUserId() {
    return this.userId;
  }

  getUserName() {
    return this.userName;
  }

  setUserName(userName) {
    this.userName = userName;
  }

  updateLocalCurrentUserShift(currentUserShift) {
    localStorage.setItem('currentUserShift', JSON.stringify(currentUserShift));
  }

  getLocalCurrentUserShift() {
    return JSON.parse(localStorage.getItem('currentUserShift'));
  }

  async insertUserCurrentShiftToPendingShifts(currentShift) {
    const pendingShifts = JSON.parse(localStorage.getItem('pendingShifts'));
    pendingShifts.push(currentShift)
    localStorage.setItem('pendingShifts', JSON.stringify(pendingShifts));
    this.updateLocalCurrentUserShift({ periods: {} });
    await this.insertPendingShiftsToFirebase();
    // localStorage.setItem('currentUserShift', JSON.stringify({}));
  }

  async insertPendingShiftsToFirebase() {
    const pendingShifts = JSON.parse(localStorage.getItem('pendingShifts'));
    console.log('pendingShifts:', pendingShifts);
    const failedToBeSentPendingShifts = [];
    for (let i = 0 ; i < pendingShifts.length ; i++) {
      try {
        const key = await this.insertUserCurrentShifttoHistory(pendingShifts[i]);
        console.log('key' , key);
      } catch (err) {
        console.log('Error while inserting into firebase', JSON.stringify(err));
        failedToBeSentPendingShifts.push(pendingShifts[i]);
      }
    }
    localStorage.setItem('pendingShifts', JSON.stringify(failedToBeSentPendingShifts));
    return true;
  }

  createFirebaseId() {
    return firebase.database().ref('/dummy').push().key;
  }

  getProducts() {
    return this.http.get(`${this.databaseUrl}/products/.json${this.authToken?('?auth='+this.authToken):''}`);
  }

  getOrganizations() {
    return this.http.get(`${this.databaseUrl}/organizations/.json${this.authToken?('?auth='+this.authToken):''}`);
  }

  insertUser(data) {
    return this.http.put(`${this.databaseUrl}/users/${data.uId}.json${this.authToken?('?auth='+this.authToken):''}`, data);
  }

  // an API to insert product views with firebase generated key
  insertProductViewAnalaytics(data) {
    return this.http.post(`${this.databaseUrl}/users/${this.userId}/product_views.json${this.authToken?('?auth='+this.authToken):''}`, data);
  }

  getProductViewsForUser() {
    return this.http.get(`${this.databaseUrl}/users/${this.userId}/product_views/.json${this.authToken?('?auth='+this.authToken):''}`);
  }

  getUserOrganization() {
    return this.http.get(`${this.databaseUrl}/users/${this.userId}/organization/.json${this.authToken?('?auth='+this.authToken):''}`);
  }

  fetchUserName() {
    return this.http.get(`${this.databaseUrl}/users/${this.userId}/userName/.json${this.authToken?('?auth='+this.authToken):''}`);
  }

  // updateUserName(data) {
  //   return this.http.patch(`${this.databaseUrl}/users/${this.userId}/.json${this.authToken?('?auth='+this.authToken):''}`, data);
  // }

  // an API to insert product views with custom timestamp based key
  insertProductViewAnalayticsTimestamp(data) {
    return this.http.put(`${this.databaseUrl}/product_views_timestamp/${data.scannedAt}.json${this.authToken?('?auth='+this.authToken):''}`, data);
  }

  // insertUserCurrentShift(data) {
  //   return this.http.patch(`${this.databaseUrl}/users/${this.userId}/currentShift.json${this.authToken?('?auth='+this.authToken):''}`, data);
  // }

  // updateUserCurrentShift(data) {
  //   return this.http.patch(`${this.databaseUrl}/users/${this.userId}/currentShift.json${this.authToken?('?auth='+this.authToken):''}`, data);
  // }

  // getUserCurrentShiftStartTime() {
  //   return this.http.get(`${this.databaseUrl}/users/${this.userId}/currentShift/currentPeriodStartedAt.json${this.authToken?('?auth='+this.authToken):''}`);
  // }

  // getUserCurrentShiftStatus() {
  //   return this.http.get(`${this.databaseUrl}/users/${this.userId}/currentShift/status.json${this.authToken?('?auth='+this.authToken):''}`);
  // }

  // insertUserPeriods(data) {
  //   return this.http.post(`${this.databaseUrl}/users/${this.userId}/currentShift/periods.json${this.authToken?('?auth='+this.authToken):''}`, data);
  // }

  // getUserCurrentShift() {
  //   return this.http.get(`${this.databaseUrl}/users/${this.userId}/currentShift.json${this.authToken?('?auth='+this.authToken):''}`);
  // }

  getPendingShifts() {
    return JSON.parse(localStorage.getItem('pendingShifts'));
  }

  async insertUserCurrentShifttoHistory(data) {
    data.userId = this.userId;
    // return firebase.database().ref('/shiftHistory').push(data).key;
    if (data.startedAt && data.endedAt) {
      return this.http.post(`${this.databaseUrl}/shiftHistory/.json${this.authToken ? ('?auth=' + this.authToken) : ''}`, data).toPromise();
    } else {
      console.log('invalid data found, not inserting into firebase', JSON.stringify(data));
      return null;
    }
  }

  // removeUserCurrentShift(){
  //   return this.http.delete(`${this.databaseUrl}/users/${this.userId}/currentShift.json${this.authToken?('?auth='+this.authToken):''}`);
  // }

  getUserWorkTimeHistory() {
    return this.http.get(`${this.databaseUrl}/shiftHistory.json${this.authToken?('?auth='+this.authToken):''}&orderBy="userId"&equalTo="${this.userId}"`);
  }

  insertUserCurrentLocation(data) {
    return this.http.post(`${this.databaseUrl}/users/${this.userId}/locationHistory.json${this.authToken?('?auth='+this.authToken):''}`, data);
  }

}

environment.prod.ts

export const environment = {
  production: true
};

environment.ts

export const environment = {
  production: false,
  firebase: {
    apiKey: "...",
    authDomain: "...",
    databaseURL: "...",
    projectId: "...",
    storageBucket: "...",
    messagingSenderId: "..."
  }
};

提前致谢!

【问题讨论】:

    标签: firebase ionic-framework firebase-realtime-database


    【解决方案1】:

    您在此处导入environment.ts:

    import { environment  } from '../environments/environment';
    

    其中包含以下内容:

    export const environment = {
      production: false,
      firebase: {
        apiKey: "...",
        authDomain: "...",
        databaseURL: "...",
        projectId: "...",
        storageBucket: "...",
        messagingSenderId: "..."
      }
    };
    

    environment 对象内没有 authToken 属性。这就是你得到这个错误的原因。

    【讨论】:

    • 你知道如何在 Firebase 上获取 authToken 吗?
    • 似乎有些不同。不知何故,这个 authToken 被用来连接到 Firebase: fetchUserName() { return this.http.get(${this.databaseUrl}/users/${this.userId}/userName/.json${this.authToken?('?auth='+this.authToken):''}); }
    • 你使用的是什么版本的 firebase?
    猜你喜欢
    • 2019-01-21
    • 2016-08-13
    • 2017-12-20
    • 2016-11-14
    • 2017-10-24
    • 2021-08-10
    • 2018-11-17
    • 2020-09-25
    • 2021-06-22
    相关资源
    最近更新 更多