limitToLast:1 个查询返回所有内容

limitToLast: 1 query returning everything

我正在使用 AngularFire2,但无法完成查询部分。 "limitToLast: 1" 正在返回所有内容,而不仅仅是我最近的条目。我需要一种方法来按顺序为我的工作编号,我正在尝试获取最新的工作 ID (4),以便我可以添加 +1 并使下一个工作成为 5.

job: FirebaseObjectObservable<any>;
test: any;

constructor(af: AngularFire) {
    this.job = af.database.object('/jobs/', {
        query:{ limitToLast: 1 }
    });
};

createNewJob(){
    this.job.subscribe(snap => {
        this.test = snap;
    });
}

我没有输出我最近的单个条目,而是得到了所有内容:

[ null, 
        { "customer": "Heather D", "description": "Work needs to be done" },
        { "customer": "Quick G", "description": "Unclog toilet" },
        { "customer": "Justin S", "description": "Do everything for everyone" }
        { "customer": "Jeff F", "description": "Ikea furniture" }
]

HTML

<button (click)="createNewJob()"> Create </button>
{{ test |  json }}

这是我的结构

ROOT
    jobs
        1
            customer: "Heather D"
            description: "Work needs to be done"
        2
            customer: "Quick G"
            description: "Unclog toilet"
        3
            customer: "Justin S"
            description: "Do everything for everyone"
        4
            customer: "Jeff F"
            description: "Ikea furniture"

更新 1:

仍然遇到同样的问题,但我觉得这是朝着正确方向迈出的一步。如我错了请纠正我。我现在给了我的工作一个唯一的 ID,这对我来说似乎是多余的,但新的结构看起来是这样的:

ROOT
    jobs
        1
            customer: "Heather D"
            description: "Work needs to be done"
            id: 1
        2
            customer: "Quick G"
            description: "Unclog toilet"
            id: 2
        3
            customer: "Justin S"
            description: "Do everything for everyone"
            id: 3
        4
            customer: "Jeff F"
            description: "Ikea furniture"
            id: 4

然后我更改了我的查询:

query:{ orderByChild: 'id', limitToLast: 1 }

同样的结果,仍然不限于一份工作。

你为什么不按工作 ID 的降序对记录进行排序并将其限制为第一个?这将为您提供最后一条记录

问题是您使用的是 object 而不是 list。使用 object 时,将忽略 query 选项。也就是说,你应该使用这样的东西:

job: FirebaseListObservable<any>;
test: any;

constructor(af: AngularFire) {
    this.job = af.database.list('/jobs/', {
        query:{ limitToLast: 1 }
    });
};

FirebaseListObservable 应该发出一个包含最后一个作业的数组。

但是,与其读取并递增最后一个作业 ID,不如使用 FirebaseListObservable 实例的 push method. See also Saving Lists of Data:

更安全

When working with lists of data push() ensures a unique and chronological key. You may be tempted to use transactions instead to generate your own keys, but push is a far better choice. Transactions are slower and more complex. They require one or more round trips to the server. A key generated by push() on the client works while offline and is optimized for performance.