AngularFireList не инициализируется в ngOnInit? - PullRequest
0 голосов
/ 14 сентября 2018

Я занимаюсь разработкой сайта, который имеет набор функций, некоторые из которых требуют аутентификации, а другие - нет.

Я успешно реализовал аутентификацию firebase без пароля по волшебной ссылке электронной почты.

Моя проблема возникает, когда пользователь вошел в систему, и я отображаю новый div (область, в которой пользователь может отслеживать свои индивидуальные цели).Мне трудно создать ссылку для отправки данных в мой список angularfirelist (goals/${user.id}).Кажется, что я не могу инициализировать эту ссылку после того, как произойдет вход в систему, и использовать идентификатор пользователя для пути ссылки, он застрял на (goals/null).

Пожалуйста, дайте мне знать, если у вас естьЛюбые идеи, как я могу создать эту ссылку базы данных после входа в систему.

Ниже я попытался обрисовать соответствующий код:

Если пользователь успешно вошел в систему, я отображаюзапрос на вставку текста в AngularFireList:

<code><ng-container *ngIf = "authService.currentUserObservable | async; else login">
  <li *ngFor = "let goal of goalsObservable | async">
    <div>
      <pre>{{ goal.payload.val() }}<button (click)=delete(goal.key) type="button" class="btn btn-default">Delete</button>
{{authService.currentUserId}} </ ng-container>

Я пытаюсь инициализировать ссылку на список базы данных в uidтекущего зарегистрированного пользователя в классе компонентов моих целей:

export class GoalsComponent implements OnInit {
  public goalsRef : AngularFireList<any>
  public goalsObservable:Observable<any[]>;
  public goalToAdd: string;
  public user: Observable<any>;
  public uid: any;
  constructor(public db: AngularFireDatabase,  private authService: AuthService, private auth: AngularFireAuth) { }
  ngOnInit() {
     if (this.authService.authenticated){ 
      this.user = this.authService.currentUserObservable;
      this.uid = this.authService.currentUserId;
      console.log(`goals/${this.uid}`);
      this.goalsRef = this.db.list(`goals/${this.uid}`);
      this.goalsObservable = this.db.list(`goals/${this.uid}`).snapshotChanges();
     }else{
       console.log("not ready to init yet...");
     }
  }

Моя служба аутентификации подписана на аутентифицированного пользователя:

export class AuthService {
  authState: any = null;
  constructor(private afAuth: AngularFireAuth) {
    this.afAuth.authState.subscribe((auth) => { this.authState = auth } );
  }
  get authenticated(): boolean {
    console.log("Authentication state = " + this.authState);
    return this.authState !== null;
  }
  get currentUser(): any {
    console.log("Current User = " + this.authState);
    return this.authenticated ? this.authState : null;
  }
  get currentUserObservable(): any {
    return this.afAuth.authState;
  }
  get currentUserId(): string {
    if (this.authenticated){
      console.log("User is logged in! ID: "+ this.authState.uid);
      return this.authState.uid;
    }
    else{
      return null;
    }
  }
  logout(){
    return this.afAuth.auth.signOut();
  }
}

Мой компонент аутентификации без пароля:

export class PasswordlessAuthComponent implements OnInit {
  user: Observable<any>;
  email: string;
  emailSent = false;
  errorMessage: string;

  constructor(public authService: AuthService, public afAuth: AngularFireAuth, 
              private router: Router, private goalsComponent: GoalsComponent) { }

  ngOnInit() {
    this.user = this.authService.currentUserObservable;
    const url = this.router.url;
    this.confirmSignIn(url);
  }
  async sendEmailLink() {
    const actionCodeSettings = {
      url: 'http://localhost:4200/login',
      handleCodeInApp: true
    };
    try {
      await this.afAuth.auth.sendSignInLinkToEmail(this.email, actionCodeSettings);
      window.localStorage.setItem('emailForSignIn', this.email);
      this.emailSent = true;
    } catch (err) {
      this.errorMessage = err.message;
    }
  }
  async confirmSignIn(url){
    try {
      if (this.afAuth.auth.isSignInWithEmailLink(url)) {
        let email = window.localStorage.getItem('emailForSignIn');
        //if missing email due to user clicking link on new device
        if (!email){
          email = window.prompt('Please provide your email for confirmation');
        }
        //signin user
        const result = await this.afAuth.auth.signInWithEmailLink(email,url);
        console.log("passwordless-auth after sign in");
        console.log(this.user);
        this.goalsComponent.update();
        window.localStorage.removeItem('emailForSignIn');
      }
    } catch (err) {
      this.errorMessage = err.message;
    }
  }
  logout(){
    return this.authService.logout()
  }
}
...