标签: angularfire2

如何检查订阅是否已完成加载所有现有行?

我想在启动时加载所有项目而不显示任何消息,但是一旦加载后.我想捕获订阅者中的任何新行并将其显示给桌面通知.

问题是,我不知道如何检查是否所有以前的项目都已加载,以及该行是新项目还是来自之前的现有项目.

this.items = this.af.database.list('notifications/'+this.uid+'/');
this.items.subscribe(list => {
    list.forEach(row => {
        // doing something here...
    });

    // once all the rows are finished loading, then any new row, show desktop notification message
});
Run Code Online (Sandbox Code Playgroud)

observable rxjs firebase firebase-realtime-database angularfire2

6
推荐指数
1
解决办法
647
查看次数

如何在angularfire2/auth signOut之后断开与Google身份验证的连接?

我正在使用Angular和Firebase构建一个网站.我正在使用Angularfire2和AngularFireAuth库以及GoogleAuthProvider(Google)作为我的身份验证提供程序.

这是我的服务代码:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';

@Injectable()
export class AuthenticationService {
  user: Observable<firebase.User>;

  constructor(public afAuth: AngularFireAuth) {
    this.user = afAuth.authState;
  }

  login() {
    this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
  }

  logout() {
    this.afAuth.auth.signOut();
  }
}
Run Code Online (Sandbox Code Playgroud)

当用户"退出"我的网站时,它可以正常工作,但似乎可以"缓存"Google身份验证.因此,当他们第二次尝试登录时,我遇到了一些问题:

  1. 用户不得选择其他Google帐户登录.
  2. 用户自动登录...这似乎是一个安全问题.另一个用户可以访问相同的共享PC,并以前一个用户身份登录,并且不需要输入密码来执行此操作.

我究竟做错了什么?有没有办法可以阻止angularfire2/auth缓存这些凭据?有没有办法在用户退出我的网站时将用户退出Google?

firebase angularfire firebase-authentication angularfire2 angular

6
推荐指数
1
解决办法
1246
查看次数

Firestore如何从另一个集合文档id获取集合值

我有两个火灾商店集合与以下参考图像.在此输入图像描述在此输入图像描述 我想获得firstNametitle.这里signup_id是从coll-signup文档id 引用的.以下代码给出了我的所作所为.

模型feed.ts

export interface Feed {
    firstName? : string;
    signup_id? : string;
    title? : string;
}
Run Code Online (Sandbox Code Playgroud)

新闻feed.component模板

    <ul *ngFor="let feed of feeds">
<!-- <li>{{feed.firstName}}</li> --> // Here I want to print my first name
      <li>{{feed.title}}</li>
      <li>{{feed.signup_id}}</li>
    </ul>
Run Code Online (Sandbox Code Playgroud)

新闻feed.component.ts

import { Component, OnInit } from '@angular/core';
import { Feed } from '../../models/feed';
import { FeedService } from '../../services/feed.service';
@Component({
  selector: 'app-news-feed',
  templateUrl: './news-feed.component.html',
  styleUrls: ['./news-feed.component.css']
})
export class NewsFeedComponent implements OnInit …
Run Code Online (Sandbox Code Playgroud)

firebase typescript angularfire2 angular google-cloud-firestore

6
推荐指数
2
解决办法
5538
查看次数

从 Firestore 获取文档时的错误处理

在带有 FireStore 和 angularfire2 的 Angular 5 中,通过控制器从服务获取文档时处理错误的正确方法是什么?

服务:

getInviteById( inviteId: string ): Promise<any> {    

    // get requested invite from firestore  
    var inviteDocument = this.afs.collection( 'invites' ).doc( inviteId );
    let invite = inviteDocument.ref.get().then( doc => {

        // if document exists
        if (doc.exists) {

            // return id and data
            const id = doc.id; 
            var data = doc.data() as any;
            return { id, ...data };

        // if document does not exist
        } else {
            console.log("Error: No such document!");

            // WHAT DO I …
Run Code Online (Sandbox Code Playgroud)

promise angularfire2 angular google-cloud-firestore

6
推荐指数
1
解决办法
1万
查看次数

Firestore + AngularFire2 分页(按范围查询项目 - .startAfter(lastVisible) )

在一个组件中,我想从 FireStore 中提取一系列项目,例如。从 0 到 5,从 5 到 10 等等。我在 FireStore 的文档中找到了这个,但是他们不使用 AngularFire2,所以我尝试重构时变得更加混乱。我通过简单的splice()'ing使它工作:

service ->

topFirstScores(): AngularFirestoreCollection<Score> {
  return this.fireRef.collection('scores', r => r
          .orderBy('score', 'desc').limit(6)
  );
}

component ->

$scores = new Subject();

this.scores$ = this.$scores.asObservable();
if (this.scores === 'first') {
  this.scoreS.topFirstScores().valueChanges().take(1)
    .subscribe(_ => this.$scores.next(_.splice(0, 3)))
} else {
  this.scoreS.topFirstScores().valueChanges().take(1)
    .subscribe(_ => this.$scores.next(_.splice(3, 3)))
}
Run Code Online (Sandbox Code Playgroud)

但这似乎更像是一种解决方法。谁能翻译一下:

var first = db.collection("cities")
        .orderBy("population")
        .limit(25);

return first.get().then(function (documentSnapshots) {
  // Get the last visible document
  var lastVisible = documentSnapshots.docs[documentSnapshots.docs.length-1]; …
Run Code Online (Sandbox Code Playgroud)

rxjs angularfire2 angular google-cloud-firestore

6
推荐指数
1
解决办法
7131
查看次数

在 Angular 单元测试中使用 firestore.Timestamp.now()

我正在开发一个带有 angularfire2 的 Angular 应用程序5.0.0-rc.10。我真的希望我不会混淆以下任何术语,但我们开始了。

我已将 Date's 转换为新的 firestore Timestamp 类型。这给我编写测试时带来了问题。我只能做到以下几点:

import { firestore } from 'firebase/app';
it ('should create', () => {
   firestore.Timestamp.now();
});
Run Code Online (Sandbox Code Playgroud)

如果我使用以下命令在 TestBed 模块中初始化 firebase:

AngularFireModule.initializeApp(environment.firebase),
Run Code Online (Sandbox Code Playgroud)

否则我得到错误:

TypeError: Cannot read property 'Timestamp' of undefined
Run Code Online (Sandbox Code Playgroud)

所以我的问题:

  1. 这是预期的行为吗?
  2. 你不应该能够在 firebase angular 项目之外创建一个 firstore Timestamp 数据类型吗?
  3. 为什么firestore undefined在没有 initializeApp 的情况下导入?

非常感谢你的帮助。

firebase angularfire2 google-cloud-firestore

6
推荐指数
1
解决办法
1526
查看次数

Firebase - 使用其他数据填充属性/数组

下面的observable创建了一个事件对象数组.

eventsRef: AngularFireList<any>;
events: Observable<any>;

this.eventsRef = db.list('events');

this.events = this.eventsRef.snapshotChanges().map(changes => {

return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
});
Run Code Online (Sandbox Code Playgroud)

我需要this.events从其他数据库列表中添加其他数据.所以我需要每个事件对象包含一个访客计数和数据eventsFilters.我不知道该怎么做.这是我到目前为止:

this.events = this.eventsRef.snapshotChanges().map(changes => {

  changes.map(data => {
    console.log(data.payload.key)
    this.db.object(`/eventsFilters/${data.payload.key}`)
      .valueChanges()
      .subscribe(data => {
         console.log(data) //event filters
      })
  })

  changes.map(data => {
    console.log(data.payload.key)
    this.db.object(`/eventsGuests/${data.payload.key}`)
      .valueChanges()
      .subscribe(data => {
        let guestCount = Object.keys(data).length;
        console.log(guestCount)
        this.guestCount = guestCount; //guest count
      })
  })
  return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
});
Run Code Online (Sandbox Code Playgroud)

编辑--------

我已经使用了这个,combineLatest但我仍然不确定如何对每个事件数据进行分组. …

javascript firebase-realtime-database angularfire2 angular

6
推荐指数
1
解决办法
111
查看次数

使用 Firebase signInWithRedirect 是否可以将其配置为将我重定向回特定页面

当我打电话

this.afAuth.auth.signInWithRedirect(provider) .then((credential) => { }) .catch((error) => this.handleError(error));

重定向工作正常,并由 firebase 处理,将我返回到登录页面。然而,承诺需要一段时间才能完成

this.afAuth.auth.getRedirectResult().then((result) => { //Login or move to request additional info });

由于页面已经完全刷新,我没有任何信息让我知道页面不应该显示登录按钮,而是应该显示加载状态。

有没有人找到解决这个问题并保持加载状态的好方法,我最初的尝试是使用角度路由来传递加载状态,但令人讨厌的是 signInWithRedirect 服务似乎没有更改它重定向到的 url。

firebase angularfire2

6
推荐指数
1
解决办法
1953
查看次数

在Observable上使用wait时,应该使用什么代替toPromise()?

此页面显示"toPromise has been deprecated! (RxJS 5.5+)"但最近我一直在AngularFire2中使用它(当我只想要一个结果时),如下所示:

const foo = await this.afs.doc(`docPath`).valueChanges().toPromise();
Run Code Online (Sandbox Code Playgroud)

我不应该这样做吗?如果没有,那有什么await选择呢?

更新:

在下面的答案之后,我对此进行了更改:

const foo = await this.afs.doc(`docPath`).valueChanges().toPromise();
Run Code Online (Sandbox Code Playgroud)

...对此:

const foo = await (new Promise(resolve => this.afs.doc(`docPath`).valueChanges().pipe(first()).subscribe(result => resolve(result))));
Run Code Online (Sandbox Code Playgroud)

有人可以向我解释这是一种改进吗?似乎向我倒退了一步。

javascript promise rxjs angularfire2 angular

6
推荐指数
1
解决办法
3256
查看次数

Angular 11 在 SSR 上运行 @nguniversal/express-engine ReferenceError: globalThis is not defined

尝试@angular/fire在 Angular 11 和@nguniversal/express-engine(SSR) 上运行。当 initAngularFireModuleapp.module.ts运行命令时有错误npm run dev:ssrnpm run serve:ssrng serve. angular 10 版本也有同样的问题。有没有人知道该怎么做?

app.module.ts:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'serverApp' }),
    AppRoutingModule,
    ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production }),
    AngularFireModule.initializeApp(environment.firebaseConfig),
    // AngularFirestoreModule,
    // AngularFirestoreModule.enablePersistence({ synchronizeTabs: true }),
    // AngularFireFunctionsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

在 server/main.js 文件中错误:

globalThis.?AngularfireInstanceCache || (globalThis.?AngularfireInstanceCache = new Map());
^

ReferenceError: globalThis …
Run Code Online (Sandbox Code Playgroud)

firebase angularfire2 angular

6
推荐指数
1
解决办法
2061
查看次数