BehaviourSubject不返回更新的数据

时间:2018-02-07 22:39:11

标签: angular typescript rxjs

我想访问Resolver上的更新数据。但是行为主题没有返回更新的数据。

我是这样做的:

ConfigService.ts(保存配置值)

@Injectable()
export class ConfigService {
 constructor() { }
 getAnsweredJsonObj() {
    const isMC =  false;
    const jsonObject = {
      country_code: 'US',
      language: 'en',
      height_inches: {foot: undefined, inches: undefined},
      goals: {},
      guest: (!isMC) ? true : false
    };
    return jsonObject;
  }
}

QuestionsService.ts

@Injectable()
export class QuestionsService {

 private answeredSubject: BehaviorSubject<any> = new BehaviorSubject<any>(this.configService.getAnsweredJsonObj());

  constructor(private configService: ConfigService) {}

  getAnsweredSubject(): Observable<any>  {
    return this.answeredSubject.asObservable();
  }

  setAnsweredSubject(answered) {
    this.answeredSubject.next(answered);
  }
}

FormComponent.ts(从组件更新behaviourSubject值)

export class FormComponent implements OnInit {

    constructor(private questionsService: QuestionsService) {}

    getResults() {
      const answered = {
          country_code: "US",
          language: "en",
          height_inches: 87,
          goals: [
              "WEIGHT",
              "PERFORMANCE",
              "AGING"
          ],
          guest: true
      };
      this.questionsService.setAnsweredSubject(answered);
      this.router.navigate(['/healthprint-results']);
  }

BundlesResolver.ts(此处使用最新的formComponent数据)

@Injectable()
export class BundlesResolver implements Resolve <any> {

    constructor(private http: HttpClient,
                private questionService: QuestionsService) {}

    resolve (route: ActivatedRouteSnapshot): Observable<any>{
        this.questionService.getAnsweredSubject().subscribe((value) => {
            console.log("Subscription got", value); // not printing the updated value
            this.answered = value;
        });

        return this.http.post('/services/getBundles', this.answered)
            .map(responseData => {
            console.log('responseData', responseData);
        });
    }
}

0 个答案:

没有答案