我有一个角度组件,它使用服务从数据库加载客户端。我不再为每个组件返回数据库,而是将此数据作为选定客户端缓存在服务中。
export class ClientService {
Clients: Client[];
constructor() {
this.Clients = [
{
client: 0,
name: "Fred",
street: "Brockton Drive",
address1: null,
address2: null,
city: "SomewhereVille",
zipcode: "1234"
},
{
client: 1,
name: "Wilma",
street: "Somerset Drive",
address1: null,
address2: null,
city: "Elsewhere",
zipcode: "0987"
},
]
}
setCurrentClient(id: number) {
var client = this.Clients[id];
console.log(client);
this.selectedClient.next(client);
}
readonly selectedClient: Subject<Client> = new Subject<Client>()
}
然后在Client组件中我订阅路由参数,并告诉客户端服务加载客户端,并设置selectedClient。
export class ClientComponent implements OnInit {
constructor(private route: ActivatedRoute, private router: Router, private clientService: ClientService) {
console.log("order component activated");
route.paramMap.subscribe((params: ParamMap) => {
const cid = params.get("id");
if (cid)
clientService.setCurrentClient(Number.parseInt(cid));
else
this.selectedClient = undefined;
})
clientService.selectedClient.subscribe((data) => this.selectedClient = data)
}
selectedClient?: Client;
ngOnInit(): void {
}
}
在Client Details组件中,我订阅了客户端服务——selected client。这是不起作用的部分。由于没有填写详细信息。
export class ClientDetailsComponent implements OnDestroy {
ClientForm: FormGroup;
token?: Subscription;
constructor(private clientService: ClientService, private formBuilder: FormBuilder) {
this.ClientForm = this.formBuilder.group<Client>(new Client());
this.token = this.clientService.selectedClient.subscribe((data) => {
this.selectedClient = data;
this.ClientForm.setValue(this.selectedClient);
console.log("Client activated");
})
}
ngOnDestroy(): void {
if(this.token) this.token.unsubscribe();
}
selectedClient?: Client;
onSubmit(): void {
}
}
我做错了什么,或者违反了最佳实践,导致这不起作用?
附言有一个 stackblitz 示例 - https://stackblitz.com/github/PhoenixStoneham/TabDataVanishing
你快到了。 问题是您使用的是主题,而不是行为主题。
这意味着它只有在开始监听后才会获取下一个值。
所以被选中的客户将不会在客户详细信息 b/c 下拥有它的价值,它不会发出任何价值。