Can't assign value to variable using subscribe() method in Angular 2

前端 未结 3 588
无人共我
无人共我 2021-02-12 13:58

The promise returns a value but I don\'t seem to be assigning the value properly in the subscribe method.

import { Component } from \'@angular/core\';
import {          


        
3条回答
  •  既然无缘
    2021-02-12 14:16

    I understand that the thread is old. So, this for the new users who are trying now. I am not sure if this is something that you are looking for. But we can persist data in a component variable albeit an ugly workaround. Here is how we used in a sample POC

    (Please use the proper hooks as subsribing to an observable is not preferred in a constructor)

            @Component({
      selector: 'app-search-promo',
      templateUrl: './search-promo.component.html',
      styleUrls: ['./search-promo.component.css']
    })
    export class SearchPromoComponent implements  AfterViewInit {
      searchGroup: FormGroup;
      stringify  =  require('json-stringify-safe');
      someResult:any;
      resp:Response;
      localInput = new FormControl('', Validators.required);
      consumedPromoList: Observable;
      constructor(private searchService: SearchService, fb: FormBuilder) {
        this.searchGroup = fb.group({
          'localInput': this.localInput
        });
         this.stringify = require('json-stringify-safe');
         this.searchService.getPromoList().subscribe(
           resp => {
             this.someResult = resp;
             console.log("Inside sub in comp"+this.stringify(resp));
             console.log("before calling the methid");
             this.callDto(resp);
           }
         );
         console.log('inside const()' + this.stringify(this.someResult));
       }
    
    callDto(data){
        console.log("caling"+data);
        this.someResult = data;
        console.log("Now priting:"+this.someResult);
        this.anotherMethod();
      }
    
      anotherMethod(){
        console.log("Inside another method"+this.stringify(this.someResult));
      }
    }
    

    That was the sample component and below is the sample service

    @Injectable()
    export class SearchService {
      getUrl: String = './../assets/promotionList.json';
      subject: BehaviorSubject = new BehaviorSubject([]); // initialize with an empty response[]
      subjectAsObservable;
       someResult;
       promoList:Promotion[];
      constructor(private http: HttpClient) {
        this.getPromoList();
        console.log("after first");
        this.getPromoValues();
        console.log("after second call");
      }
    
        getPromoList(){
        // by default it emits a response of Json and hence Observabpe
        // throws an error
        this.someResult = this.http.get(`${this.getUrl}`);
        console.log("before map"+> this.someResult);
        return (> this.someResult);
        //console.log("first subsriber"+JSON.stringify (this.someResult);
    
      }
    

提交回复
热议问题