从http分配值以获取对角度变量的响应

时间:2019-04-16 07:14:09

标签: angular typescript

我正在创建一个具有幻灯片切换功能的设置应用程序。当前我正在使用本地存储来保存切换状态。但是我想根据服务器响应来更改切换阶段。我想根据设置的值来切换按钮在数据库中。但是我很不愿意获取这些值。我能够记录整个响应,但是我不知道如何从该http响应中获取值。请帮忙。谢谢

这是我的代码:

组件

export class PolicyComponent implements OnInit {

      @Output() change: EventEmitter<MatSlideToggleChange>;
      @Input() checked: boolean;

      isChecked = true;
      formGroup: FormGroup;
      filteringSchedule: boolean;
      toggle: boolean;

      policy:Policy[];
      constructor(
        private formBuilder: FormBuilder,private policyService:PolicyService
      ) { }

      ngOnInit() {
        this.filteringSchedule = JSON.parse(sessionStorage.getItem('toggleButtonState'));
        this.formGroup = this.formBuilder.group({
          enableWifi: this.filteringSchedule,
          acceptTerms: [false, Validators.requiredTrue]
        });

        this.policyService.getPolicy().subscribe(
        (response)=>{
    console.log(response);    })


      }

  onFormSubmit(formValue: any) {
    alert(JSON.stringify(formValue, null, 2));
  }

  onChange(ob: MatSlideToggleChange) {
    this.filteringSchedule = !this.filteringSchedule;
    sessionStorage.setItem('toggleButtonState', JSON.stringify(this.filteringSchedule));
  }

}

型号:

export class Policy
{
    id:number;
    policy1:string;
    policy2:string;
}

服务:

export class PolicyService {

  constructor(private http:HttpClient) { }
  baseUrl:string="/policy";

  getPolicy()
  {
    return this.http.get<Policy[]>(this.baseUrl);

  }
}

响应为:

[
    {
        "id": 1,
        "policy1": "a",
        "policy2": "b"
    }
]

2 个答案:

答案 0 :(得分:0)

据我所见,您应该更改此代码:

   this.policyService.getPolicy().subscribe(
    (response)=>{
console.log(response);    })

this.policyService.getPolicy().subscribe(
        response => {
             this.policy = response;
        })

答案 1 :(得分:0)

我想你快到了。只需将响应保存在组件的变量中即可:

export class PolicyComponent implements OnInit {
  serverData: any;

  ngOnInit() {
    this.filteringSchedule = JSON.parse(sessionStorage.getItem('toggleButtonState'));
    this.formGroup = this.formBuilder.group({
      enableWifi: this.filteringSchedule,
      acceptTerms: [false, Validators.requiredTrue]
    });

    this.policyService.getPolicy().subscribe(
      (response)=>{
        console.log(response);   

        this.serverData = response; // maybe you also want to only store one property, eg. this.serverData = response.data; 
     })
  }
}

现在您可以在HTML中访问该变量:

<div *ngFor="let policy of serverData">
  {{policy.policy1}}
  <p *ngIf="policy.policy2"> 
    This has another policy: {{policy.policy2}}
  </p>
</div>