我正在努力学习angular 14中的变化,特别是inject()
特性,在这里我可以将模块注入函数,而不需要为此创建特殊服务..但我想我做错了什么.
我试图创建一些静态函数来使用包ngx-toastr
发送零食消息,但这个包与我的问题无关.我如何正确地实现显示零食消息的功能,同时向它们注入它们需要操作的模块.
这是我的messages.ts
文件:
import {inject} from '@angular/core';
import {ToastrService} from 'ngx-toastr';
export const snackMsgSuccess = (msg: string, title?: string) => {
const toaster = inject(ToastrService);
toaster.success(msg, title, {
easeTime: 1000
});
};
export const snackMsgInfo = (msg: string, title?: string) => {
const toaster = inject(ToastrService);
toaster.info(msg, title, {
easeTime: 1000
});
};
export const snackMsgWarn = (msg: string, title?: string) => {
const toaster = inject(ToastrService);
toaster.warning(msg, title, {
easeTime: 1000
});
};
export const snackMsgError = (msg: string, title?: string) => {
const toaster = inject(ToastrService);
toaster.error(msg, title, {
easeTime: 1000
});
};
我得到了以下错误:
Error: Uncaught (in promise): Error: NG0203: inject() must be called from an injection context (a constructor, a factory function or a field initializer)
好我以前try 使用支持函数获取路由参数时遇到了一个问题:
export const routeParam$ = (key: string) => {
const activatedRoute = inject(ActivatedRoute);
return activatedRoute.params.pipe(
pluck(key),
filter(r => r !== null),
distinctUntilChanged()
);
};
我只能在task: Observable<string> = routeParam$('task');
的组件中用作字段初始值设定项
嗯,错误信息非常清楚...但仍然..我对angular14是新手,我想注射可以让我做到这一点.否则对我没什么用处.
现在我把它作为一种服务来移动..
import {Injectable} from '@angular/core';
import {ToastrService} from 'ngx-toastr';
@Injectable({
providedIn: 'root'
})
export class MsgService {
constructor(private toaster: ToastrService) {
}
public snackMsgSuccess = (msg: string, title?: string) => {
this.toaster.success(msg, title, {
easeTime: 1000
});
};
public snackMsgInfo = (msg: string, title?: string) => {
this.toaster.info(msg, title, {
easeTime: 1000
});
};
public snackMsgWarn = (msg: string, title?: string) => {
this.toaster.warning(msg, title, {
easeTime: 1000
});
};
public snackMsgError = (msg: string, title?: string) => {
this.toaster.error(msg, title, {
easeTime: 1000
});
};
}
但这是实现它的唯一途径吗?甚至在angular14?