最后一个迭代值出现在所有对象中

last iterated value is coming in all objects

我正在为每个父迭代项迭代一个集合文档和一个子迭代。

public getxxxxxTimings(key : string) : any {

    console.log('key '+key);
    return this.afs.collection('/xxxxx/'+key+'/slots').doc('1').ref.get().then((doc)=>{

        let json = doc.data();
        console.log('json data '+json);
        console.log("Document keys:", Object.keys(json));
        Object.keys(json).forEach((name) => {
            this.timingRef = new Timing();
            console.log('name '+name);
            this.timingRef.slot = name;
            this.timingRef.available = json[name];
            this.afs.collection('/slots/').doc(name).ref.get().then((doc)=>{
                let json2 = doc.data();
                console.log('json data '+json2);
                console.log("Document keys:", Object.keys(json2));
                Object.keys(json2).forEach((name2) => {

                    if(name2 == 'from'){
                        this.timingRef.from = json2[name2];
                    }
                    else{
                        this.timingRef.to = json2[name2];
                    }

                })

                console.log('Timings count '+this.Timings.push(this.timingRef));

            })

        })

        return this.Timings;


    });



  }

在上面的代码中,父循环在每次迭代中准备一个对象并将其推送到集合中。 问题是,所有对象都被最后迭代的值填充,其中日志按预期显示。

key -KiDPBvL9xG7_hAQ0kpv
timingmodal.ts:29 key -KiDPBvL9xG7_hAQ0kpv
user-service.ts:119 key -KiDPBvL9xG7_hAQ0kpv
timingmodal.ts:38 ionViewDidLoad TimingmodalPage
user-service.ts:123 json data [object Object]
user-service.ts:124 Document keys: (4) ["1", "2", "3", "5"]
user-service.ts:127 name 1
user-service.ts:127 name 2
user-service.ts:127 name 3
user-service.ts:127 name 5
user-service.ts:132 json data [object Object]
user-service.ts:133 Document keys: (2) ["from", "to"]
user-service.ts:145 Timings count 1
user-service.ts:132 json data [object Object]
user-service.ts:133 Document keys: (2) ["from", "to"]
user-service.ts:145 Timings count 2
user-service.ts:132 json data [object Object]
user-service.ts:133 Document keys: (2) ["from", "to"]
user-service.ts:145 Timings count 3
user-service.ts:132 json data [object Object]
user-service.ts:133 Document keys: (2) ["from", "to"]
user-service.ts:145 Timings count 4

UI写成

<ul>
  <li *ngFor="let timing of Timings | async">
    {{ timing.slot }} -{{ timing.from }} -- {{ timing.to }}-- {{ timing.available }} 
  </li>
</ul>

值呈现如下。

理想情况下,它应该像..

1-9-10--真

2-10-11--真

3-11-12--假

5-13-14--真

我这里漏了什么,请指教。

将全局 timingRef 对象替换为本地引用后,它可以正常工作并正确呈现。

this.timingRef = new Timing(); => let timingRef = new Timing(); 

感谢 user184994,his/her 评论给了我一个思考的提示。