Angular语言 - 带参数的InjectionToken



我有一个InjectionToken:

export const SOURCE_DATA_INJECTION_TOKEN =
new InjectionToken<CustomObject[]>('All Source Data', {
providedIn: 'root',
factory: () => {
// Returns all source
return someArrayData // This data is read from a local .json file;
}
});

我的组件直接使用它,

@Component({})
export class SourceManager {
sourceDataList: CustomObject[] = inject(SOURCE_DATA_INJECTION_TOKEN);
}

现在,我必须升级我的INJECTION_TOKEN以根据用户在Component中选择的源返回数据。组件中的更新看起来像这样:

@Component({})
export class SourceManager {
selectedSource: SourceEnum = SourceEnum.SomeSource1
sourceDataList: CustomObject[] = inject(SOURCE_DATA_INJECTION_TOKEN);
}

selectedSource可从UI更改。我想将这个selectedSourceenum发送到我的注入令牌,而不是返回所有源,现在令牌将返回过滤的数据。

我看到工厂方法也可以有参数,我可以通过某种方式传递selectedSource给它吗?

不将SOURCE_DATA_INJECTION_TOKEN更改为可观察对象,不幸的是,您没有太多选项。现在我能想到的只有这个

https://stackblitz.com/edit/angular-easguk?file=src%2Fmain.ts


type Datum = {
id: string;
};
export const SOURCE_ADD_TOKEN = new InjectionToken<Subject<Datum>>(
'Add Source',
{
providedIn: 'root',
factory: () => new Subject<Datum>(),
}
);
export const SOURCE_DATA_INJECTION_TOKEN = new InjectionToken<Datum[]>(
'All Source Data',
{
providedIn: 'root',
factory: () => {
let items = [{ id: '0' }];
inject(SOURCE_ADD_TOKEN).subscribe((newItem) => {
items.push(newItem);
});
return items;
},
}
);
@Component({
selector: 'my-app',
standalone: true,
template: `
We have {{data.length}} item(s)
<button (click)="onChangeClick()">Add</button>
`,
})
export class App {
public data = inject(SOURCE_DATA_INJECTION_TOKEN);
private add$ = inject(SOURCE_ADD_TOKEN);
onChangeClick() {
this.add$.next({ id: nanoid() });
}
}

相关内容

  • 没有找到相关文章

最新更新