将http get响应值分配给angular中的变量

问题描述 投票:-1回答:2

我正在创建一个具有幻灯片切换的设置应用程序。目前我正在使用本地存储来保存切换状态。但是我想根据服务器响应更改切换阶段。我想根据数据库中设置的值切换按钮。但我无法获取值。我能够记录整个响应,但我不知道如何从该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"
    }
]
angular typescript
2个回答
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>

0
投票

从我所看到的,您应该更改此代码:

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

this.policyService.getPolicy().subscribe(
        response => {
             this.policy = response;
        })
© www.soinside.com 2019 - 2024. All rights reserved.