Angular 角度服务中字符串函数的返回值
我需要在角度服务中实现一个函数,该函数返回一个Angular 角度服务中字符串函数的返回值,angular,typescript,ionic-framework,Angular,Typescript,Ionic Framework,我需要在角度服务中实现一个函数,该函数返回一个x值,然后在任何组件中检索该值。我使用本机存储来存储值,然后我需要从任何地方访问它,因此制作angular服务器是最好的方法 这是我的当前实现,但当我尝试在页面中获取值时,会返回一个未定义的值: getValue(){ 设x; 这 .functionUtil .getItems('someValue') 。然后(项目=>{ if(items&&items.length!=0){ x=项目[0]; } }); 返回x; }这不起作用,因为承诺是异步的
x
值,然后在任何组件中检索该值。我使用本机存储来存储值,然后我需要从任何地方访问它,因此制作angular服务器是最好的方法
这是我的当前实现,但当我尝试在页面中获取值时,会返回一个未定义的值:
getValue(){
设x;
这
.functionUtil
.getItems('someValue')
。然后(项目=>{
if(items&&items.length!=0){
x=项目[0];
}
});
返回x;
}
这不起作用,因为承诺是异步的。按时间顺序,会发生以下情况:x
被声明,x
被返回(值未定义),Promise解析并更改函数中的x
,但由于未定义的已返回,它实际上什么也不做
最好的方法是返回一个新的承诺,保持你的价值
getValue() {
return this
.functionUtil
.getItems('someValye')
.then(items => {
if (items && items.length != 0) {
return items[0];
} else {
return undefined;
}
});
}
或使用异步等待:
async getValue() {
const items = await this
.functionUtil
.getItems('someValye');
if (items && items.length != 0) {
return items[0];
}
}
组成部分
这不起作用,因为承诺是异步的。按时间顺序,会发生以下情况:
x
被声明,x
被返回(值未定义),Promise解析并更改函数中的x
,但由于未定义的已返回,它实际上什么也不做
最好的方法是返回一个新的承诺,保持你的价值
getValue() {
return this
.functionUtil
.getItems('someValye')
.then(items => {
if (items && items.length != 0) {
return items[0];
} else {
return undefined;
}
});
}
或使用异步等待:
async getValue() {
const items = await this
.functionUtil
.getItems('someValye');
if (items && items.length != 0) {
return items[0];
}
}
组成部分
这就是为什么要进行异步操作。 改写如下:
getValue(): Promise<any> {
return this
.functionUtil
.getItems('someValye')
.then(items => items && items.length != 0
? items[0] : null);
}
或者可以像上面的注释一样使用AsyncWait:)
请记住,承诺解决问题可能需要一些时间,这取决于你的逻辑。您还可以在模板中直接使用Promise和异步管道:
{{value | async}}
这就是为什么要进行异步操作。 改写如下:
getValue(): Promise<any> {
return this
.functionUtil
.getItems('someValye')
.then(items => items && items.length != 0
? items[0] : null);
}
或者可以像上面的注释一样使用AsyncWait:)
请记住,承诺解决问题可能需要一些时间,这取决于你的逻辑。您还可以在模板中直接使用Promise和异步管道:
{{value | async}}
在服务内部,打印在函数Utils上获得的项目。在服务中.then(items=>{console.log(JSON.stringfy(items))…}之后,打印在函数Utils上得到的项。紧接着.then(items=>{console.log(JSON.stringfy(items))…}