首页 > 解决方案 > 从http分配值以获取对角度变量的响应

问题描述

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

标签: angulartypescript

解决方案


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

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

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

推荐阅读