Issue
I need to load all /assets local folder before my app init. Now only images that I currently need when the app starts are being loaded. How to avoid that and load all of them?
Solution
You can create a file.txt in your assets folder (*) with all the files, read using httpClient and read the images. Some like
export function initializeAppFactory(httpClient: HttpClient):
() => Observable<any> {
return ()=>
httpClient.get('./assets/files.txt',{responseType: 'text'})
.pipe(switchMap((res:any)=>{
const files=res.split("\r\n")
return forkJoin(files
.map((f:string)=>httpClient.get('./assets/'+f,
{ observe: 'response' })))
}),tap(()=>{
console.log("ready")
}))
}
(*)It's difficult read the files of a directory
A stackblitz (see that in console goes "ready" before show the application and using F12 you see that the files are readed)
Update
Aclaration about the code: The idea is that, e.g. res get the value "file1.jpg\n\rfile2.jpg\n\r", files becomes
["file1.jpg","file2.jpg"]`, the forkjoin makes all the calls.
So, possible we need need filter to be sure the files has value:
const files=res.split("\r\n").filter((x:any)=>x)
This avoid if in files.txt there're a new line. BTW We can check the Check the response when you read the file
console.log(res,files)
Well, we can improve the function to take account we add a file that not exist.
export function initializeAppFactory(
httpClient: HttpClient
): () => Observable<any> {
return () =>
httpClient.get('./assets/files.txt', { responseType: 'text' }).pipe(
switchMap((res: any) => {
const files = res.split('\r\n').filter((x: any) => x);
return forkJoin(
files.map((f: string) =>
httpClient.get('./assets/' + f, { observe: 'response' }).pipe(
catchError((error: any) => {
console.log('file not found: ' + f, error);
return EMPTY;
})
)
)
);
}),
tap(() => {
console.log('ready');
})
);
}
just update in the stackblitz
Answered By - Eliseo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.