Angular 18 component does not work as expected with blobs

Discussão em 'Angular' iniciado por Bijaya Rai, Novembro 20, 2024.

  1. Bijaya Rai

    Bijaya Rai Guest

    I have an angular 18 project which pulls the image data from an API to dispaly's it on screen. Can someone help me understand this behaviour?

    The app throws an exception 'document is not defined' with the 'const a = document.createElement('a');' in the getImage(..) function of the ImageService.ts file. Even with this error, the app pulls the image data and draws it on the page.

    [​IMG]

    When I take this line out, I get a different error and the image also does not show.

    [​IMG]

    I added a breakpoint on the API and also the getImage function in ImageService.ts, when I refresh the page, the server API breakpoint is hit even before the breakpoints in the getImage function.

    Is there a new way in which Observable are serviced or could it be an issue related to angular hooks?

    ImageService.ts

    @Injectable({
    providedIn: 'root'
    })
    export class ImageService {

    private apiUrl = 'http://localhost:5189/LoadImage';

    constructor(private http: HttpClient) { }

    getImage(objectId: string): Observable<Blob> {
    const a = document.createElement('a');
    return this.http.get(`${this.apiUrl}/${objectId}`, {responseType: 'blob' });
    }
    }


    Image.component.ts

    @Component({
    selector: 'app-image',
    templateUrl: './image.component.html',
    styleUrls: ['./image.component.css'],
    standalone: true,
    imports:[CommonModule]
    })
    export class ImageComponent implements OnInit {
    imageUrl: any;

    constructor(private imageService: ImageService) {}

    async ngOnInit(): Promise<void> {
    (await this.imageService.getImage('apple')).subscribe({
    next: (blob) => {
    const objectURL = URL.createObjectURL(blob);
    this.imageUrl = objectURL;
    }}
    );
    }
    }
    }


    Image.component.html:

    <div>
    <img [src]="imageUrl" alt="Image" />
    </div>


    App.component.html

    <app-image></app-image>

    Continue reading...

Compartilhe esta Página