如何 return 来自服务方法的数据并订阅该方法
How to return data from a method in a service and subscribe to that method
我的问题很简单。我有一项服务,我在其中添加了一种名为 getBillingWeeks
的方法。此方法将调用 API(间接)并且它应该 return 正确的数据。我的问题是,当我在我的 angular 组件中订阅此方法时,我得到 undefined
。这是代码:
我正在创建一个服务,其中我将保留一些可以由多个组件 called/shared 的方法。这是我的代码:
common.service.ts
...
@Injectable({
providedIn: 'root'
})
export class CommonService {
billingWeeks = new Subject<FilterOption[]>();
constructor(private _someOtherService: SomeOtherService) { }
getBillingWeeks() {
this._someOtherService
.getBillingWeeksFromDatabase()
.pipe(take(1))
.subscribe((data: BillingWeek[]) => {
this.billingWeeks = data.map((item: BillingWeek) => {
return new FilterOption(
item.shortName,
item.fullName
);
});
return this.billingWeeks;
});
}
}
my.component.ts
constructor(
private _commonService: CommonService
) {}
ngOnInit(): void {
console.log(this._commonService.getBillingWeeks());
}
无论我在哪里放置 return 语句,我都会得到 undefined
。请纠正我的错误。
这个设计有很多问题。它应该是这样的
common.service.ts
@Injectable({
providedIn: 'root',
})
export class CommonService {
constructor(private _someOtherService: SomeOtherService) {}
getBillingWeeks() {
return this._someOtherService.getBillingWeeksFromDatabase().pipe(
take(1),
map((data: BillingWeek[]) =>
data.map(
(item: BillingWeek) => new FilterOption(item.shortName, item.fullName)
)
)
);
}
}
my.component.ts
constructor(private _commonService: CommonService) {}
ngOnInit(): void {
this._commonService
.getBillingWeeks()
.subscribe((data: FilterOption[]) => console.log(data));
}
我的问题很简单。我有一项服务,我在其中添加了一种名为 getBillingWeeks
的方法。此方法将调用 API(间接)并且它应该 return 正确的数据。我的问题是,当我在我的 angular 组件中订阅此方法时,我得到 undefined
。这是代码:
我正在创建一个服务,其中我将保留一些可以由多个组件 called/shared 的方法。这是我的代码:
common.service.ts
...
@Injectable({
providedIn: 'root'
})
export class CommonService {
billingWeeks = new Subject<FilterOption[]>();
constructor(private _someOtherService: SomeOtherService) { }
getBillingWeeks() {
this._someOtherService
.getBillingWeeksFromDatabase()
.pipe(take(1))
.subscribe((data: BillingWeek[]) => {
this.billingWeeks = data.map((item: BillingWeek) => {
return new FilterOption(
item.shortName,
item.fullName
);
});
return this.billingWeeks;
});
}
}
my.component.ts
constructor(
private _commonService: CommonService
) {}
ngOnInit(): void {
console.log(this._commonService.getBillingWeeks());
}
无论我在哪里放置 return 语句,我都会得到 undefined
。请纠正我的错误。
这个设计有很多问题。它应该是这样的
common.service.ts
@Injectable({
providedIn: 'root',
})
export class CommonService {
constructor(private _someOtherService: SomeOtherService) {}
getBillingWeeks() {
return this._someOtherService.getBillingWeeksFromDatabase().pipe(
take(1),
map((data: BillingWeek[]) =>
data.map(
(item: BillingWeek) => new FilterOption(item.shortName, item.fullName)
)
)
);
}
}
my.component.ts
constructor(private _commonService: CommonService) {}
ngOnInit(): void {
this._commonService
.getBillingWeeks()
.subscribe((data: FilterOption[]) => console.log(data));
}