Angular 5数据绑定问题

时间:2018-04-06 06:12:22

标签: angular data-binding 2-way-object-databinding

我是角度5中的菜鸟尝试在API调用的结果中设置多个变量,但是变量的变化在视图中没有反映,尽管在控制台上记录变量会在组件(ts文件或控制器)中显示其值。

在以下代码中,对partnerPlanInfo varibale的更改将反映在视图中,但对servData1变量的更改未在视图中反映。

所以请指导我在哪里遗漏导致此问题的事情。

    import { Component, OnInit, ViewEncapsulation } from '@angular/core';
    import { MerchantService } from '../merchant.service';
    import {Observable} from 'rxjs/Rx';
    import { HttpClient, HttpParams } from '@angular/common/http';
    import { Plan } from '../models/Plan';
    import {ChangeDetectorRef} from '@angular/core';
    import { ChangeDetectionStrategy } from '@angular/core';

    @Component({
     selector: 'app-dashboard',
     templateUrl: './dashboard.component.html',
     styleUrls: [
    './dashboard.component.scss',
    './merchantAdd.scss',
    './intlTelInput.scss',
    './checkbox.scss',
    './merchant_type.scss',
    './redeemlocation.scss',

    ],
    encapsulation: ViewEncapsulation.None,
    providers:[MerchantService, HttpClient] ,
    changeDetection: ChangeDetectionStrategy.OnPush
    })
    export class DashboardComponent implements OnInit {
    public merchants;
    public partnerPlanInfo;
    public customPlan;
    public planServices: any[]  = new Array();
    public planInfo: any;
    public planService: any;
    public serviceData:any[] = new Array();
    public planInfoArray: any[] = new Array();
    public servData: any;
    public servData1: any[]=  new Array();


    constructor(private _merchantServices: MerchantService,private   
    ref:ChangeDetectorRef) {

     }

  ngOnInit() {

   this.getPartnerPlan();
   //let timer = Observable.timer(2000, 5000);
  // timer.subscribe(() => this.getPartnerPlan());
  }

  getPartnerPlan()
  {
    let partnerPlanRequestData  = new HttpParams().set('partnerId','prtnr000000000000001').set('planType','0');



    this._merchantServices.getPlan(partnerPlanRequestData).subscribe( // the first argument is a function which runs on success
      parnerPlan => { this.partnerPlanInfo = parnerPlan;


       this.servData1= this.generateServiceData(parnerPlan);

        console.log(this.servData1);

        this.ref.detectChanges();
      },
      // the second argument is a function which runs on error
      err => console.error(err),
      // the third argument is a function which runs on completion
      () => console.log('done loading partner plan'+this.partnerPlanInfo)
    );
    //console.log(this.planServices);


  }


  generateServiceData(parnerPlan)
  {
    let count=0;
    for (this.planInfo of parnerPlan){
      var planArray:any[] = new Array();
      planArray[this.planInfo.id] = this.planInfo.planServicesDetail;
      console.log(planArray);
      this.serviceData[count]=planArray;
      count++;
          }
    return this.serviceData;

        }

      }

的console.log(this.servData1);将结果显示为

[planm000000000000016: [0: {insertMode: false, flags: "0000000000", createdOn: "2018-02-23T07:19:23", updatedOn: "2018-02-23T07:19:23", createdBy: "admin"}]]

但是servData1的值没有反映在视图中。当我像{{servData1}}一样打印它时,它会显示为,。 当我尝试使用

在视图中循环servData1时
<div *ngFor="let ser of servData1">
  <p>{{ ser }}</p>
</div>

然后显示

<!--bindings={
  "ng-reflect-ng-for-of": ",,"
}-->

4 个答案:

答案 0 :(得分:0)

尝试像这样打印

<div *ngFor="let ser of servData1">
  <div *ngFor="let serDetails of ser">{{serDetails.insertMode }}</div>
</div>

答案 1 :(得分:0)

public static void AddUserScript(UserScripts entity, string RavendbUrl, int userid) { try { IvcRavenDB raven = new IvcRavenDB(); var store = raven.InitRavenDB(RavendbUrl, "UserScripts"); entity.Updated = DateTime.Now.ToString(); entity.Created = DateTime.Now.ToString(); entity.ScriptFileLength = entity.Script.Length; entity.userid = userid; using (var session = store.OpenSession()) { session.Store(entity); // DIES HERE session.SaveChanges(); } } catch (Exception ex) { var mess = ex.Message; } } 的数据结构似乎是这样的

servData1

表示你有一个带有map的数组,地图中的每个条目都是一个带有map的新数组。你需要一个双循环来打印你最内层的物体。

尝试

[id:
  [0:{},
   1:{},
   n:{}
  ]
]

这将在数据结构中最内层元素内打印对象。添加了json管道只是为了使打印漂亮。可能不需要它。

答案 2 :(得分:0)

尝试以这种方式使用管道,但需要根据您的对象属性进行配置:

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push({key: key, value: value[key]});
    }
    return keys;
  }
}

您的代码是:

<div *ngFor="let ser of servData1 | keys">
  <div *ngFor="let serDetails of ser">{{serDetails.insertMode }}</div>
</div>

或将你的json转换为componet中的key对象

Object.keys(servData1);

答案 3 :(得分:0)

servData1中的对象值不是有效的JSON。 enter image description here

因此无法序列化为数组。 在发送此

之前删除服务器上的斜杠