Angular 在本地存储中缓存 http
Angular cache http in local storage
在 Ionic 4 Angular 8 项目上,我尝试在调用前获取存储中的信息 API。
这是我的代码
public getData(id) {
return this.storage.get(id).then(
content => {
if (content == null) {
return this.getObject(id).subscribe(
result => {
return result;
}
);
} else {
return content;
}
}
);
}
如何调用“getData”函数?
myService.getData(id).then
我应该订阅这个 return 字符串或可观察对象,如何处理这两种情况?
您正在寻找这样的东西吗?
public getData(id): Observable<any> {
return this.storage.get(id)
.then(content => {
if (content === null) {
return this.getObject(id);
} else {
return of(content);
}
}
}
然后你就可以这样称呼它了:
myService.getData(id).subscribe(console.log);
更新
你能试试这个吗?
getData(id): Observable<any> {
return Observable.fromPromise(this.storage.get(id)).switchMap(content => {
if (content === null) {
return this.getObject(id);
} else {
return of(content);
}
})
}
如果您使用的是 RxJS 6,我建议您将 promise 转换为可观察对象(使用 from operator), and then handle the subsequent operations using pipeable operators, such as tap
, or switchMap
, depending on the desired behaviour of your method. In this case, we can use switchMap,因为我们正在 return 可观察对象。
import { from } from 'rxjs';
import { switchMap } from 'rxjs/operators';
getData(id) {
return from(this.storage.get(id))
.pipe(
switchMap(content => {
if (content === null) {
return this.getObject(id);
} else {
return of(content);
}
}),
)
}
从那里,您可以订阅 getData
和 return 观察值。
myService.getData(id).subscribe((res) => {
// do the rest here
})
在 Ionic 4 Angular 8 项目上,我尝试在调用前获取存储中的信息 API。
这是我的代码
public getData(id) {
return this.storage.get(id).then(
content => {
if (content == null) {
return this.getObject(id).subscribe(
result => {
return result;
}
);
} else {
return content;
}
}
);
}
如何调用“getData”函数?
myService.getData(id).then
我应该订阅这个 return 字符串或可观察对象,如何处理这两种情况?
您正在寻找这样的东西吗?
public getData(id): Observable<any> {
return this.storage.get(id)
.then(content => {
if (content === null) {
return this.getObject(id);
} else {
return of(content);
}
}
}
然后你就可以这样称呼它了:
myService.getData(id).subscribe(console.log);
更新
你能试试这个吗?
getData(id): Observable<any> {
return Observable.fromPromise(this.storage.get(id)).switchMap(content => {
if (content === null) {
return this.getObject(id);
} else {
return of(content);
}
})
}
如果您使用的是 RxJS 6,我建议您将 promise 转换为可观察对象(使用 from operator), and then handle the subsequent operations using pipeable operators, such as tap
, or switchMap
, depending on the desired behaviour of your method. In this case, we can use switchMap,因为我们正在 return 可观察对象。
import { from } from 'rxjs';
import { switchMap } from 'rxjs/operators';
getData(id) {
return from(this.storage.get(id))
.pipe(
switchMap(content => {
if (content === null) {
return this.getObject(id);
} else {
return of(content);
}
}),
)
}
从那里,您可以订阅 getData
和 return 观察值。
myService.getData(id).subscribe((res) => {
// do the rest here
})