【发布时间】:2019-09-12 08:59:32
【问题描述】:
我正在使用 BehaviorSubject 来保存与其他组件共享的变量(用户名),它在我的模板上显示用户名的效果很好。但是,我希望能够在服务中使用我的 BehaviorSubject 的值,然后将该值(用户名)用作如下方法的参数:myMethod(username){ do stuff }。
问题似乎在于调用该方法时 BehaviorSubject 值尚未准备好。我已经尝试在构造函数和 ngOnInIt 中调用该方法,如果我将它记录到控制台,它首先显示它是未定义的,然后最终它使用正确的(用户名)值记录。是否可以使用 BehaviorSubject 获取作为参数传递给方法的值?
在我的示例中,我有一个 auth.service,其中包含我的 BehaviorSubject(不显示登录/身份验证内容,因为它与此示例无关)。然后在我的 newform.component.ts 中订阅了那个 BehaviorSubject。我可以在新表单模板上显示值,但这不是我想要做的。 我正在努力的是订阅 newform.component 中的 BehaviorSubject 值并将其传递给一个调用服务的方法,该服务应该根据用户名返回一个位置数组。我需要该位置数组来填充新表单模板上的输入,这就是我尝试在 ngOnInIt 上调用它的原因......所以我可以在用户开始填写表单之前获取输入的位置。
下面是一些代码:
auth.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private accountInfoSource = new BehaviorSubject<any>({});
accountInfoCurrent = this.accountInfoSource.asObservable();
constructor() { }
accountInfoChange(accountName: any) {
this.accountInfoSource.next(accountName)
}
}
newform.component.ts
import { Component, OnInit } from '@angular/core';
import { Locationslist } from '../services/locationslist.service';
import { AuthService } from '../services/auth.service';
@Component({
selector: 'app-new-charge',
templateUrl: './new-charge.component.html',
styleUrls: ['./new-charge.component.css']
})
export class NewChargeComponent implements OnInit {
accountName: string;
locations;
constructor(protected authService: AuthService, private locations: Locationslist) { }
ngOnInit() {
this.getLocations();
}
getLocations() {
this.authService.accountInfoCurrent.subscribe(accountInfo => {
this.accountName = accountInfo.AccountName;
} );
this.locations.getUserLocations(this.accountName) // <=== this.accountName is undefined
.subscribe(foundset => {
this.locations = foundset;
});
}
}
locationslist.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class Valuelists {
constructor(private http: HttpClient, protected authService: AuthService) { }
getUserLocations(accountname) {
let token = localStorage.getItem('token');
let body = '{\"query\": [ { \"AccountName\" : \"=' + accountname + '\"} ] }';
const findLocations = 'https://my.api';
let auth = 'Bearer ' + token;
return this.http.post(findLocations, body, {
headers: new HttpHeaders()
.set('Content-Type', 'application/json')
.set('Access-Control-Allow-Origin', '*')
.set('Authorization', auth)
})
}
}
如果我将“帐户名”硬编码到 getUserLocations(accountname) 的参数中,我知道位置列表服务可以工作。事实上,locationservice 最终会使用 BehaviorSubject 值,但在控制台中我首先看到一个错误,http 响应为 500,然后我最终获得了位置信息。再一次,似乎 BehaviorSubject 变量出现得很晚。有没有办法将 BehaviorSubject 值作为参数传递给方法,还是有更好的方法来实现我的目标?
【问题讨论】:
-
感谢大家的意见和帮助。我最终使用路由参数将数据从一个组件发送到下一个组件。将“参数”传递给另一个组件的“正确”方式更直接,更有可能是“正确”的方式(名称路由参数!)。
标签: angular typescript behaviorsubject