在没有用户$ uid的情况下,如何在访问者区域中获得与在管理员区域中相同的对象

时间:2018-10-12 13:46:16

标签: javascript angular firebase firebase-realtime-database rxjs

目前在一个博客网站上,像我遇到的一个问题,当我开始构建它时就没想到...

我这样构建它:

•一个必须登录的管理区域,您可以在其中写/删除文章。

•无需登录的公共区域,即可在管理区域中看到撰写的文章。

我的数据库的构建如下所示,您可以看到每个用户都有一个$ uid。因此,由于其构建方式,我的服务如下所示:

{
  "articles" : {
    "xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
      "-LORxrYnctixsx5sQ5DM" : {
        "author" : "Zinedine Zidane",
        "categories" : [ "Football", "Tennis" ],
        "content" : "<p>Constituendi autem sunt qui sint in amicitia fines et quasi termini diligendi. De quibus tres video sententias ferri, quarum nullam probo, unam, ut eodem modo erga amicum adfecti simus, quo erga nosmet ipsos, alteram, ut nostra in amicos benevolentia illorum erga nos benevolentiae pariter aequaliterque respondeat, tertiam, ut, quanti quisque se ipse facit, tanti fiat ab amicis.Constituendi autem sunt qui sint in amicitia fines et quasi termini diligendi. De quibus tres video sententias ferri, quarum nullam probo, unam, ut eodem modo erga amicum adfecti simus, quo erga nosmet ipsos, alteram, ut nostra in amicos benevolentia illorum erga nos benevolentiae pariter aequaliterque respondeat, tertiam, ut, quanti quisque se ipse facit, tanti fiat ab amicis.</p>",
        "date" : 1539158014424,
        "image" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/41666967_311898482736538_5532086598150712503_n.jpg?alt=media&token=6b13fe37-357e-45db-8d0e-4436e166d359",
        "name" : "Thalassio otium quem et hortaretur. \t"
      },
      "-LORy85GKdT9U9p_Iolk" : {
        "author" : "David Kidouille",
        "categories" : [ "Football", "ChatMignon" ],
        "content" : "<p>Ego vero sic intellego, Patres conscripti, nos hoc tempore in provinciis decernendis perpetuae pacis habere oportere rationem. Nam quis hoc non sentit omnia alia esse nobis vacua ab omni periculo atque etiam suspicione belli?Ego vero sic intellego, Patres conscripti, nos hoc tempore in provinciis decernendis perpetuae pacis habere oportere rationem. Nam quis hoc non sentit omnia alia esse nobis vacua ab omni periculo atque etiam suspicione belli?</p>",
        "date" : 1539158086263,
        "image" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/36981961_1869531810009121_4498273348232413184_n.jpg?alt=media&token=47fc2e67-d198-4533-8939-abc5d3dbed51",
        "name" : "Omni habere atque perpetuae sic."
      },
      "-LOTQNaI7ry3WRavCjNt" : {
        "author" : "Sophia Green",
        "categories" : [ "Espresso", "Title" ],
        "content" : "<p>Harum trium sententiarum nulli prorsus assentior. Nec enim illa prima vera est, ut, quem ad modum in se quisque sit, sic in amicum sit animatus. Quam multa enim, quae nostra causa numquam faceremus, facimus causa amicorum! precari ab indigno, supplicare, tum acerbius in aliquem invehi insectarique vehementius, quae in nostris rebus non satis honeste, in amicorum fiunt honestissime; multaeque res sunt in quibus de suis commodis viri boni multa detrahunt detrahique patiuntur, ut iis amici potius quam ipsi fruantur.</p><p>Ibi victu recreati et quiete, postquam abierat timor, vicos opulentos adorti equestrium adventu cohortium, quae casu propinquabant, nec resistere planitie porrecta conati digressi sunt retroque concedentes omne iuventutis robur relictum in sedibus acciverunt.</p><p>Non ergo erunt homines deliciis diffluentes audiendi, si quando de amicitia, quam nec usu nec ratione habent cognitam, disputabunt. Nam quis est, pro deorum fidem atque hominum! qui velit, ut neque diligat quemquam nec ipse ab ullo diligatur, circumfluere omnibus copiis atque in omnium rerum abundantia vivere? Haec enim est tyrannorum vita nimirum, in qua nulla fides, nulla caritas, nulla stabilis benevolentiae potest esse fiducia, omnia semper suspecta atque sollicita, nullus locus amicitiae.</p>",
        "date" : 1539182528987,
        "image" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/37112713_499156913858390_6321776699583234048_n.jpg?alt=media&token=dea02d84-dcc8-427e-92d1-92529499e052",
        "name" : "Plerisque honoribus inventu in verae descendant quas in graves enim"
      }
    }
  },
  "contact" : {
    "xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
      "adress" : "Bla Bla Bla",
      "email" : "michel@gmail.com",
      "facebook" : "www.facebook.com",
      "phone" : "0606060606"
    }
  },
  "evenements" : {
    "xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
      "-LORx0d49L5W1OHbaPkz" : {
        "content" : "<p>Eodem tempore Serenianus ex duce, cuius ignavia populatam in Phoenice Celsen ante rettulimus, pulsatae maiestatis imperii reus iure postulatus ac lege, incertum qua potuit suffragatione absolvi, aperte convictus familiarem suum cum pileo, quo caput operiebat, incantato vetitis artibus ad templum misisse fatidicum, quaeritatum expresse an ei firmum portenderetur imperium, ut cupiebat, et cunctum.</p>",
        "dateEnd" : "20/08/1995",
        "dateStart" : "17/08/1995",
        "name" : "Stand de tir au pigeon",
        "place" : "33 rue de la Liberté, Bourgoin Jallieu"
      }
    }
  },
  "medias" : {
    "xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
      "-LORymdySlsQ82_rZ6kk" : {
        "description" : "Bla Bla Bla Bla",
        "titre" : "30 ans de michel",
        "type" : "image",
        "url" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/41466540_333985383837957_6494746608337518152_n.jpg?alt=media&token=079311d7-c42e-4e21-933e-36573e88a893"
      },
      "-LORyzf8ft5hS_MV_B10" : {
        "description" : "klsjbvsjdkbvjkshd",
        "titre" : "Bla Bla bla",
        "type" : "image",
        "url" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/41532985_724838064517122_5880047170186967403_n.jpg?alt=media&token=86632def-47b3-4b30-84c9-c9af571da17d"
      }
    }
  },
  "sports" : {
    "xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
      "-LORzZ2xq_JszbFaFyyn" : {
        "description" : "<p>Nec vox accusatoris ulla licet subditicii in his malorum quaerebatur acervis ut saltem specie tenus crimina praescriptis legum committerentur, quod aliquotiens fecere principes saevi: sed quicquid Caesaris implacabilitati sedisset, id velut fas iusque perpensum confestim urgebatur impleri.</p>",
        "handisport" : "<p>Ego vero sic intellego, Patres conscripti, nos hoc tempore in provinciis decernendis perpetuae pacis habere oportere rationem. Nam quis hoc non sentit omnia alia esse nobis vacua ab omni periculo atque etiam suspicione belli?</p>",
        "image" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/42004027_2218122771593693_1511293494740179714_n.jpg?alt=media&token=430ddee9-a818-44ac-b80c-2483be38f1c0",
        "name" : "Football",
        "nbrPlayer" : 10,
        "partTime" : 30
      }
    }
  }
}

我在管理区域中可以访问$ uid的服务

import { Injectable } from '@angular/core';

import { filter, map, tap } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';

import { AngularFireDatabase } from 'angularfire2/database';

import { Store } from '../../store';

import { AuthService } from './auth.service';

export interface Article {
    name: string,
    author: string,
    categories: string[],
    content: string,
    date: string,
    image: string,
    key: string,
    $exists: () => boolean
  }

@Injectable()
export class ArticlesService {


    articles$ = this.db.list<Article>(`articles/${this.uid}`).snapshotChanges()
        .pipe(map(actions => 
            actions.map(a => ({ key: a.key, ...a.payload.val() }))
        ))
        .pipe(tap(next => {
            this.store.set('articles', next);
        })
    );

    constructor(
        private store: Store,
        private db: AngularFireDatabase,
        private authService: AuthService
    ) {}

    get uid() {
        return this.authService.user.uid;
    }

    getArticle(key: string) {
        if (!key) return of({});
        return this.store.select<Article[]>(`articles`)
            .pipe(filter(Boolean))
            .pipe(map(articles => articles.find((article: Article) => article.key === key)));
    }

    addArticle(article: Article) {
        return this.db.list(`articles/${this.uid}`).push(article);
    }

    updateArticle(key: string, article: Article) {
        return this.db.object(`articles/${this.uid}/${key}`).update(article);
    }

    removeArticle(key: string) {
        return this.db.list(`articles/${this.uid}`).remove(key);
    }

}

我在无法访问$ uid的管理区域中的服务

import { Injectable } from '@angular/core';

import { filter, map, tap } from 'rxjs/operators';
import { of } from 'rxjs';

import { AngularFireDatabase } from 'angularfire2/database';

import { Store } from '../../store';



export interface Article {
    name: string,
    author: string,
    category: string[],
    content: string,
    date: string,
    image: string,
    key: string,
    $exists: () => boolean
  }

@Injectable()
export class ArticlesService {


    articles$ = this.db.list<Article>(`articles`).snapshotChanges()
        .pipe(map(userId =>   
            userId.map(a => ({ ...a.payload.val() }))
        )).pipe(tap(next => {
            this.store.set('articles', next);
        }));

    constructor(
        private store: Store,
        private db: AngularFireDatabase
    ) {}

        getArticle(key: string) {
            if (!key) return of({});
            return this.store.select<Article[]>(`articles`)
                .pipe(filter(Boolean))
                .pipe(map(articles => articles.find((article: Article) => article.key === key)));
        }

}

因此,当我致电该服务以在管理区域get和公共区域get中获取文章时。

我找到了一种获取值的方法,但是用这种方法我丢失了关键对象。

export interface Article {
    name: string,
    author: string,
    category: string[],
    content: string,
    date: string,
    image: string,
    key: string,
    $exists: () => boolean
  }

如何在访问者区域中获得与在管理区域中相同的对象?

0 个答案:

没有答案