刷新页面之前未在登录时获取ID-Angular

刷新页面之前未在登录时获取ID-Angular,angular,typescript,angularfire,getter,Angular,Typescript,Angularfire,Getter,我正在处理Angular项目,在登录后第一次路由到页面时,我没有获取用于在firebase firestore集合中搜索的authService.currentUserId 我必须刷新页面才能让它工作,然后我就不会再出现错误了。当我使用myregisterWithEmail功能并加载页面,但不使用myloginWithEmail功能时,不会发生此错误 auth.Service.ts import {Injectable} from '@angular/core'; import {Angula

我正在处理Angular项目,在登录后第一次路由到页面时,我没有获取用于在firebase firestore集合中搜索的
authService.currentUserId

我必须刷新页面才能让它工作,然后我就不会再出现错误了。当我使用my
registerWithEmail
功能并加载页面,但不使用my
loginWithEmail
功能时,不会发生此错误

auth.Service.ts

import {Injectable} from '@angular/core';
import {AngularFireAuth} from '@angular/fire/auth';
import {Router} from '@angular/router';
import {AngularFirestore} from '@angular/fire/firestore';
import {CompanyUserInterface} from '../../models/companyuser';


@Injectable({
  providedIn: 'root'
})
export class AuthService {

  authState: any = null;

  constructor(private afAuth: AngularFireAuth, private router: Router, public fireService: AngularFirestore) {
    this.afAuth.authState.subscribe((auth => {
      this.authState = auth;
    }));
  }

  // is called when company register. creates firebase auth login with email and password
  // this also creates a document with the information from the registration in the collection companies
  registerWithEmail(email: string, password: string, companyUser: CompanyUserInterface) {
    console.log(email, password);
    return this.afAuth.createUserWithEmailAndPassword(email, password).then((data) => {
      console.log('reg email', data);
      this.authState = data;
      // Gets user id and added to company for unique id
      companyUser.UID = data.user.uid;
      return this.fireService.collection('companies').add(Object.assign({}, companyUser));
    }).catch(error => {
      console.log(error);
      throw error;
    });
  }

  // is called in login and checks if login info is correct in firebase
  loginWithEmail(email: string, password: string) {
    return this.afAuth.signInWithEmailAndPassword(email, password).then((data) => {
      this.authState = data;
    })
      .catch(error => {
        console.log(error);
        throw error;
      });
  }


  logout(): void {
    this.afAuth.signOut().then();
    this.router.navigate(['/login']).then();
  }

  // all firebase getter functions
  get isUserAnonymousLoggedIn(): boolean {
    return (this.authState !== null) ? this.authState.isAnonymous : false;
  }

  get currentUserId(): string {
    return (this.authState !== null) ? this.authState.uid : '';
  }

  get currentUserName(): string {
    return this.authState.email;
  }

  get currentUser(): any {
    return (this.authState !== null) ? this.authState : null;
  }

  get isUserEmailLoggedIn(): boolean {
    return (this.authState !== null) && (!this.isUserAnonymousLoggedIn);
  }
}
import {Component, OnInit} from '@angular/core';
import {AuthService} from '../../services/auth/auth.service';
import {Router} from '@angular/router';

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

  email = '';
  password = '';
  errorMessage = ''; // validation error handling
  error: { name: string, message: string } = {name: '', message: ''}; // for firebase error handling

  constructor(private authService: AuthService, private router: Router) {
  }

  ngOnInit(): void {
  }

  // checks with firebase is user info is inputted and then if its valid. routes to userinfo site
  login() {
    this.clearErrorMessage();
    if (this.validateForm(this.email, this.password)) {
      this.authService.loginWithEmail(this.email, this.password).then(() => {
          this.router.navigate(['schedule']).then();
        }).catch(error => {
        this.error = error;
        this.router.navigate(['login']).then();
      });
    }
  }
}
import {Component, OnInit} from '@angular/core';
import {AuthService} from '../../services/auth/auth.service';
import {Router} from '@angular/router';
import {NgbModal, NgbModalConfig} from '@ng-bootstrap/ng-bootstrap';
import {CompanyUserInterface, CompanyUser} from '../../models/companyuser';

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

  companyUser: CompanyUserInterface;
  password = '';

  message = '';
  errorMessage = ''; // validation error handling
  error: { name: string, message: string } = {name: '', message: ''}; // for firebase error handling

  constructor(public authService: AuthService,
              private router: Router,
              private config: NgbModalConfig,
              private modalService: NgbModal,
  ) {
    // customize default values of modals used by this component tree
    config.backdrop = 'static';
    config.keyboard = false;
    this.companyUser = new CompanyUser('', '', '', '', '');
  }

  ngOnInit(): void {
  }

  // register company/association. checks if value are true before creating with authService
  // sends company info from registry to create new doc in collection
  registerWithEmail(content) {
    this.clearErrorMessage();
    console.log(this.companyUser);
    if (this.validateRegisterForm(this.companyUser.email, this.password)) {
      this.authService.registerWithEmail(this.companyUser.email, this.password, this.companyUser).then(() => {
        this.modalService.open(content);
        this.router.navigate(['userinfo']).then();
        this.message = '\nCongratulations on creating your profile\n'.toUpperCase();
      }).catch(error => {
        this.error = error;
        this.router.navigate(['register']).then();
      });
    }
  }
}
import {Injectable} from '@angular/core';
import {AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument} from '@angular/fire/firestore';
import {ScheduleInterface} from '../../models/schedule';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {AuthService} from '../auth/auth.service';


@Injectable({
  providedIn: 'root'
})
export class ScheduleService {
  schedulesCollection: AngularFirestoreCollection<ScheduleInterface>;
  schedules: Observable<ScheduleInterface[]>;
  scheduleDoc: AngularFirestoreDocument<ScheduleInterface>;

  constructor(private afs: AngularFirestore, public authService: AuthService) {
  }

  getSchedules(): Observable<ScheduleInterface[]> {
    // I'm not getting my authService currentUserId on the first call.
    console.log('test in getSchedules', this.authService.currentUserId);
    return this.afs.collection('schedules', (ref) => ref
      .where('UID', '==', this.authService.currentUserId)
      .orderBy('user', 'asc'))
      .snapshotChanges()
      .pipe(
        map((changes) =>
          changes.map((a) => {
            const data = a.payload.doc.data() as ScheduleInterface;
            data.docRef = a.payload.doc.id;
            return data;
          })
        )
      );
  }
}
login.components.ts

import {Injectable} from '@angular/core';
import {AngularFireAuth} from '@angular/fire/auth';
import {Router} from '@angular/router';
import {AngularFirestore} from '@angular/fire/firestore';
import {CompanyUserInterface} from '../../models/companyuser';


@Injectable({
  providedIn: 'root'
})
export class AuthService {

  authState: any = null;

  constructor(private afAuth: AngularFireAuth, private router: Router, public fireService: AngularFirestore) {
    this.afAuth.authState.subscribe((auth => {
      this.authState = auth;
    }));
  }

  // is called when company register. creates firebase auth login with email and password
  // this also creates a document with the information from the registration in the collection companies
  registerWithEmail(email: string, password: string, companyUser: CompanyUserInterface) {
    console.log(email, password);
    return this.afAuth.createUserWithEmailAndPassword(email, password).then((data) => {
      console.log('reg email', data);
      this.authState = data;
      // Gets user id and added to company for unique id
      companyUser.UID = data.user.uid;
      return this.fireService.collection('companies').add(Object.assign({}, companyUser));
    }).catch(error => {
      console.log(error);
      throw error;
    });
  }

  // is called in login and checks if login info is correct in firebase
  loginWithEmail(email: string, password: string) {
    return this.afAuth.signInWithEmailAndPassword(email, password).then((data) => {
      this.authState = data;
    })
      .catch(error => {
        console.log(error);
        throw error;
      });
  }


  logout(): void {
    this.afAuth.signOut().then();
    this.router.navigate(['/login']).then();
  }

  // all firebase getter functions
  get isUserAnonymousLoggedIn(): boolean {
    return (this.authState !== null) ? this.authState.isAnonymous : false;
  }

  get currentUserId(): string {
    return (this.authState !== null) ? this.authState.uid : '';
  }

  get currentUserName(): string {
    return this.authState.email;
  }

  get currentUser(): any {
    return (this.authState !== null) ? this.authState : null;
  }

  get isUserEmailLoggedIn(): boolean {
    return (this.authState !== null) && (!this.isUserAnonymousLoggedIn);
  }
}
import {Component, OnInit} from '@angular/core';
import {AuthService} from '../../services/auth/auth.service';
import {Router} from '@angular/router';

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

  email = '';
  password = '';
  errorMessage = ''; // validation error handling
  error: { name: string, message: string } = {name: '', message: ''}; // for firebase error handling

  constructor(private authService: AuthService, private router: Router) {
  }

  ngOnInit(): void {
  }

  // checks with firebase is user info is inputted and then if its valid. routes to userinfo site
  login() {
    this.clearErrorMessage();
    if (this.validateForm(this.email, this.password)) {
      this.authService.loginWithEmail(this.email, this.password).then(() => {
          this.router.navigate(['schedule']).then();
        }).catch(error => {
        this.error = error;
        this.router.navigate(['login']).then();
      });
    }
  }
}
import {Component, OnInit} from '@angular/core';
import {AuthService} from '../../services/auth/auth.service';
import {Router} from '@angular/router';
import {NgbModal, NgbModalConfig} from '@ng-bootstrap/ng-bootstrap';
import {CompanyUserInterface, CompanyUser} from '../../models/companyuser';

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

  companyUser: CompanyUserInterface;
  password = '';

  message = '';
  errorMessage = ''; // validation error handling
  error: { name: string, message: string } = {name: '', message: ''}; // for firebase error handling

  constructor(public authService: AuthService,
              private router: Router,
              private config: NgbModalConfig,
              private modalService: NgbModal,
  ) {
    // customize default values of modals used by this component tree
    config.backdrop = 'static';
    config.keyboard = false;
    this.companyUser = new CompanyUser('', '', '', '', '');
  }

  ngOnInit(): void {
  }

  // register company/association. checks if value are true before creating with authService
  // sends company info from registry to create new doc in collection
  registerWithEmail(content) {
    this.clearErrorMessage();
    console.log(this.companyUser);
    if (this.validateRegisterForm(this.companyUser.email, this.password)) {
      this.authService.registerWithEmail(this.companyUser.email, this.password, this.companyUser).then(() => {
        this.modalService.open(content);
        this.router.navigate(['userinfo']).then();
        this.message = '\nCongratulations on creating your profile\n'.toUpperCase();
      }).catch(error => {
        this.error = error;
        this.router.navigate(['register']).then();
      });
    }
  }
}
import {Injectable} from '@angular/core';
import {AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument} from '@angular/fire/firestore';
import {ScheduleInterface} from '../../models/schedule';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {AuthService} from '../auth/auth.service';


@Injectable({
  providedIn: 'root'
})
export class ScheduleService {
  schedulesCollection: AngularFirestoreCollection<ScheduleInterface>;
  schedules: Observable<ScheduleInterface[]>;
  scheduleDoc: AngularFirestoreDocument<ScheduleInterface>;

  constructor(private afs: AngularFirestore, public authService: AuthService) {
  }

  getSchedules(): Observable<ScheduleInterface[]> {
    // I'm not getting my authService currentUserId on the first call.
    console.log('test in getSchedules', this.authService.currentUserId);
    return this.afs.collection('schedules', (ref) => ref
      .where('UID', '==', this.authService.currentUserId)
      .orderBy('user', 'asc'))
      .snapshotChanges()
      .pipe(
        map((changes) =>
          changes.map((a) => {
            const data = a.payload.doc.data() as ScheduleInterface;
            data.docRef = a.payload.doc.id;
            return data;
          })
        )
      );
  }
}
register.components.ts

import {Injectable} from '@angular/core';
import {AngularFireAuth} from '@angular/fire/auth';
import {Router} from '@angular/router';
import {AngularFirestore} from '@angular/fire/firestore';
import {CompanyUserInterface} from '../../models/companyuser';


@Injectable({
  providedIn: 'root'
})
export class AuthService {

  authState: any = null;

  constructor(private afAuth: AngularFireAuth, private router: Router, public fireService: AngularFirestore) {
    this.afAuth.authState.subscribe((auth => {
      this.authState = auth;
    }));
  }

  // is called when company register. creates firebase auth login with email and password
  // this also creates a document with the information from the registration in the collection companies
  registerWithEmail(email: string, password: string, companyUser: CompanyUserInterface) {
    console.log(email, password);
    return this.afAuth.createUserWithEmailAndPassword(email, password).then((data) => {
      console.log('reg email', data);
      this.authState = data;
      // Gets user id and added to company for unique id
      companyUser.UID = data.user.uid;
      return this.fireService.collection('companies').add(Object.assign({}, companyUser));
    }).catch(error => {
      console.log(error);
      throw error;
    });
  }

  // is called in login and checks if login info is correct in firebase
  loginWithEmail(email: string, password: string) {
    return this.afAuth.signInWithEmailAndPassword(email, password).then((data) => {
      this.authState = data;
    })
      .catch(error => {
        console.log(error);
        throw error;
      });
  }


  logout(): void {
    this.afAuth.signOut().then();
    this.router.navigate(['/login']).then();
  }

  // all firebase getter functions
  get isUserAnonymousLoggedIn(): boolean {
    return (this.authState !== null) ? this.authState.isAnonymous : false;
  }

  get currentUserId(): string {
    return (this.authState !== null) ? this.authState.uid : '';
  }

  get currentUserName(): string {
    return this.authState.email;
  }

  get currentUser(): any {
    return (this.authState !== null) ? this.authState : null;
  }

  get isUserEmailLoggedIn(): boolean {
    return (this.authState !== null) && (!this.isUserAnonymousLoggedIn);
  }
}
import {Component, OnInit} from '@angular/core';
import {AuthService} from '../../services/auth/auth.service';
import {Router} from '@angular/router';

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

  email = '';
  password = '';
  errorMessage = ''; // validation error handling
  error: { name: string, message: string } = {name: '', message: ''}; // for firebase error handling

  constructor(private authService: AuthService, private router: Router) {
  }

  ngOnInit(): void {
  }

  // checks with firebase is user info is inputted and then if its valid. routes to userinfo site
  login() {
    this.clearErrorMessage();
    if (this.validateForm(this.email, this.password)) {
      this.authService.loginWithEmail(this.email, this.password).then(() => {
          this.router.navigate(['schedule']).then();
        }).catch(error => {
        this.error = error;
        this.router.navigate(['login']).then();
      });
    }
  }
}
import {Component, OnInit} from '@angular/core';
import {AuthService} from '../../services/auth/auth.service';
import {Router} from '@angular/router';
import {NgbModal, NgbModalConfig} from '@ng-bootstrap/ng-bootstrap';
import {CompanyUserInterface, CompanyUser} from '../../models/companyuser';

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

  companyUser: CompanyUserInterface;
  password = '';

  message = '';
  errorMessage = ''; // validation error handling
  error: { name: string, message: string } = {name: '', message: ''}; // for firebase error handling

  constructor(public authService: AuthService,
              private router: Router,
              private config: NgbModalConfig,
              private modalService: NgbModal,
  ) {
    // customize default values of modals used by this component tree
    config.backdrop = 'static';
    config.keyboard = false;
    this.companyUser = new CompanyUser('', '', '', '', '');
  }

  ngOnInit(): void {
  }

  // register company/association. checks if value are true before creating with authService
  // sends company info from registry to create new doc in collection
  registerWithEmail(content) {
    this.clearErrorMessage();
    console.log(this.companyUser);
    if (this.validateRegisterForm(this.companyUser.email, this.password)) {
      this.authService.registerWithEmail(this.companyUser.email, this.password, this.companyUser).then(() => {
        this.modalService.open(content);
        this.router.navigate(['userinfo']).then();
        this.message = '\nCongratulations on creating your profile\n'.toUpperCase();
      }).catch(error => {
        this.error = error;
        this.router.navigate(['register']).then();
      });
    }
  }
}
import {Injectable} from '@angular/core';
import {AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument} from '@angular/fire/firestore';
import {ScheduleInterface} from '../../models/schedule';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {AuthService} from '../auth/auth.service';


@Injectable({
  providedIn: 'root'
})
export class ScheduleService {
  schedulesCollection: AngularFirestoreCollection<ScheduleInterface>;
  schedules: Observable<ScheduleInterface[]>;
  scheduleDoc: AngularFirestoreDocument<ScheduleInterface>;

  constructor(private afs: AngularFirestore, public authService: AuthService) {
  }

  getSchedules(): Observable<ScheduleInterface[]> {
    // I'm not getting my authService currentUserId on the first call.
    console.log('test in getSchedules', this.authService.currentUserId);
    return this.afs.collection('schedules', (ref) => ref
      .where('UID', '==', this.authService.currentUserId)
      .orderBy('user', 'asc'))
      .snapshotChanges()
      .pipe(
        map((changes) =>
          changes.map((a) => {
            const data = a.payload.doc.data() as ScheduleInterface;
            data.docRef = a.payload.doc.id;
            return data;
          })
        )
      );
  }
}
时间表.服务.ts

import {Injectable} from '@angular/core';
import {AngularFireAuth} from '@angular/fire/auth';
import {Router} from '@angular/router';
import {AngularFirestore} from '@angular/fire/firestore';
import {CompanyUserInterface} from '../../models/companyuser';


@Injectable({
  providedIn: 'root'
})
export class AuthService {

  authState: any = null;

  constructor(private afAuth: AngularFireAuth, private router: Router, public fireService: AngularFirestore) {
    this.afAuth.authState.subscribe((auth => {
      this.authState = auth;
    }));
  }

  // is called when company register. creates firebase auth login with email and password
  // this also creates a document with the information from the registration in the collection companies
  registerWithEmail(email: string, password: string, companyUser: CompanyUserInterface) {
    console.log(email, password);
    return this.afAuth.createUserWithEmailAndPassword(email, password).then((data) => {
      console.log('reg email', data);
      this.authState = data;
      // Gets user id and added to company for unique id
      companyUser.UID = data.user.uid;
      return this.fireService.collection('companies').add(Object.assign({}, companyUser));
    }).catch(error => {
      console.log(error);
      throw error;
    });
  }

  // is called in login and checks if login info is correct in firebase
  loginWithEmail(email: string, password: string) {
    return this.afAuth.signInWithEmailAndPassword(email, password).then((data) => {
      this.authState = data;
    })
      .catch(error => {
        console.log(error);
        throw error;
      });
  }


  logout(): void {
    this.afAuth.signOut().then();
    this.router.navigate(['/login']).then();
  }

  // all firebase getter functions
  get isUserAnonymousLoggedIn(): boolean {
    return (this.authState !== null) ? this.authState.isAnonymous : false;
  }

  get currentUserId(): string {
    return (this.authState !== null) ? this.authState.uid : '';
  }

  get currentUserName(): string {
    return this.authState.email;
  }

  get currentUser(): any {
    return (this.authState !== null) ? this.authState : null;
  }

  get isUserEmailLoggedIn(): boolean {
    return (this.authState !== null) && (!this.isUserAnonymousLoggedIn);
  }
}
import {Component, OnInit} from '@angular/core';
import {AuthService} from '../../services/auth/auth.service';
import {Router} from '@angular/router';

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

  email = '';
  password = '';
  errorMessage = ''; // validation error handling
  error: { name: string, message: string } = {name: '', message: ''}; // for firebase error handling

  constructor(private authService: AuthService, private router: Router) {
  }

  ngOnInit(): void {
  }

  // checks with firebase is user info is inputted and then if its valid. routes to userinfo site
  login() {
    this.clearErrorMessage();
    if (this.validateForm(this.email, this.password)) {
      this.authService.loginWithEmail(this.email, this.password).then(() => {
          this.router.navigate(['schedule']).then();
        }).catch(error => {
        this.error = error;
        this.router.navigate(['login']).then();
      });
    }
  }
}
import {Component, OnInit} from '@angular/core';
import {AuthService} from '../../services/auth/auth.service';
import {Router} from '@angular/router';
import {NgbModal, NgbModalConfig} from '@ng-bootstrap/ng-bootstrap';
import {CompanyUserInterface, CompanyUser} from '../../models/companyuser';

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

  companyUser: CompanyUserInterface;
  password = '';

  message = '';
  errorMessage = ''; // validation error handling
  error: { name: string, message: string } = {name: '', message: ''}; // for firebase error handling

  constructor(public authService: AuthService,
              private router: Router,
              private config: NgbModalConfig,
              private modalService: NgbModal,
  ) {
    // customize default values of modals used by this component tree
    config.backdrop = 'static';
    config.keyboard = false;
    this.companyUser = new CompanyUser('', '', '', '', '');
  }

  ngOnInit(): void {
  }

  // register company/association. checks if value are true before creating with authService
  // sends company info from registry to create new doc in collection
  registerWithEmail(content) {
    this.clearErrorMessage();
    console.log(this.companyUser);
    if (this.validateRegisterForm(this.companyUser.email, this.password)) {
      this.authService.registerWithEmail(this.companyUser.email, this.password, this.companyUser).then(() => {
        this.modalService.open(content);
        this.router.navigate(['userinfo']).then();
        this.message = '\nCongratulations on creating your profile\n'.toUpperCase();
      }).catch(error => {
        this.error = error;
        this.router.navigate(['register']).then();
      });
    }
  }
}
import {Injectable} from '@angular/core';
import {AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument} from '@angular/fire/firestore';
import {ScheduleInterface} from '../../models/schedule';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {AuthService} from '../auth/auth.service';


@Injectable({
  providedIn: 'root'
})
export class ScheduleService {
  schedulesCollection: AngularFirestoreCollection<ScheduleInterface>;
  schedules: Observable<ScheduleInterface[]>;
  scheduleDoc: AngularFirestoreDocument<ScheduleInterface>;

  constructor(private afs: AngularFirestore, public authService: AuthService) {
  }

  getSchedules(): Observable<ScheduleInterface[]> {
    // I'm not getting my authService currentUserId on the first call.
    console.log('test in getSchedules', this.authService.currentUserId);
    return this.afs.collection('schedules', (ref) => ref
      .where('UID', '==', this.authService.currentUserId)
      .orderBy('user', 'asc'))
      .snapshotChanges()
      .pipe(
        map((changes) =>
          changes.map((a) => {
            const data = a.payload.doc.data() as ScheduleInterface;
            data.docRef = a.payload.doc.id;
            return data;
          })
        )
      );
  }
}
从'@angular/core'导入{Injectable};
从'@angular/fire/firestore'导入{AngularFirestore,AngularFirestoreCollection,AngularFirestoreDocument};
从“../../models/schedule”导入{ScheduleInterface};
从“rxjs”导入{Observable};
从“rxjs/operators”导入{map};
从“../auth/auth.service”导入{AuthService};
@注射的({
providedIn:'根'
})
导出类ScheduleService{
schedulesCollection:AngularFirestoreCollection;
时间表:可观察;
scheduleDoc:AngularFirestoreDocument;
构造函数(私有afs:AngularFirestore,公共authService:authService){
}
getSchedules():可观察{
//第一次调用时,我无法获取authService currentUserId。
log('testingetschedules',this.authService.currentUserId);
返回此.afs.collection('schedules',(ref)=>ref
.where('UID','=',this.authService.currentUserId)
.orderBy('user','asc'))
.snapshotChanges()
.烟斗(
映射((更改)=>
更改。映射((a)=>{
const data=a.payload.doc.data()作为ScheduleInterface;
data.docRef=a.payload.doc.id;
返回数据;
})
)
);
}
}

我没有看到在任何组件中注入ScheduleService。您需要注入该服务才能使用它,并且在ScheduleService中注入AuthService as auth service之后注入它。AuthService应该在ScheduleService初始化之前进行初始化。

假设您使用的是标准依赖项注入,每次都会实例化一个新的服务实例,因此不会存储服务类中的字段,如
authState

使用本地存储或会话存储来存储这些数据。例如,

保存:

loginWithEmail(email: string, password: string) {
    return this.afAuth.signInWithEmailAndPassword(email, password).then((data) => {
      // this.authState = data;
      // uid is the variable containing your value to save
      localStorage.setItem('uid', data.uid);
      // If you want to use the sessionStorage
      // sessionStorage.setItem('uid', data.uid);
    })
      .catch(error => {
        console.log(error);
        throw error;
      });
  }
装载:

getSchedules(): Observable<ScheduleInterface[]> {
    return this.afs.collection('schedules', (ref) => ref
      .where('UID', '==', localStorage.getItem('uid')) // <--- Here
      .orderBy('user', 'asc'))
      .snapshotChanges()
      .pipe(
        map((changes) =>
          changes.map((a) => {
            const data = a.payload.doc.data() as ScheduleInterface;
            data.docRef = a.payload.doc.id;
            return data;
          })
        )
      );
  }
清除本地存储,即清空它(移除本地存储中存储的所有密钥)


成功登录后,此.afAuth.signInWithEmailAndPassword()函数返回的
数据是什么?角度版本在哪里执行调用
getSchedules()
?您的
getSchedules()
函数在流中调用得太快,但在当前代码中,我们看不到调用在任何地方发生。请提供一个最小的可复制代码示例作为起点,例如,中的角度项目。这样帮助你就容易多了。更多信息请访问