How to display image thumbnail using angular image upload - javascript

I am using ng2-file-upload to upload the image. Everything works well but after i choose image, it'll display selected image thumbnail.
Please review my stackblitz Link
Thanks in Advance

You can look out this demo may this helps you
Template file:
img element to show image preview
<img [src]="previewImg" *ngIf="previewImg"/>
Class file:
URL.createObjectURL() is a static method that creates a DOMString containing a URL representing the object given in the parameter.
bypassSecurityTrustUrl Bypass security and trust the given value to be a safe style URL, i.e. a value that can be used in hyperlinks or <img src>.
constructor(private sanitizer: DomSanitizer) {} // inject the DomSanitizer
previewImg: SafeUrl;
this.uploader.onAfterAddingFile = (file) => {
console.log('***** onAfterAddingFile ******')
this.previewImg = this.sanitizer.bypassSecurityTrustUrl((window.URL.createObjectURL(file._file)));;
}
Dont forget to include import { DomSanitizer, SafeUrl } from '#angular/platform-browser';

Here is the answer when your image is ready using FileReader show the thumbnail
import { Component, OnInit } from '#angular/core';
import {FileUploader} from 'ng2-file-upload';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
url = 'https://evening-anchorage-3159.herokuapp.com/api/';
ready = false;
thumb="";
uploader = new FileUploader({
url: this.url,
maxFileSize: 1024 * 1024 * 1
});
name = 'Angular 5';
ngOnInit() {
this.uploader.onAfterAddingFile = (file) => {
console.log('***** onAfterAddingFile ******')
var image_file=file._file
const reader = new FileReader();
reader.addEventListener('load', () => {
console.log(reader.result)
this.ready=true;
this.thumb=reader.result.toString();
});
reader.readAsDataURL(image_file);
}
this.uploader.onCompleteItem = (item:any, response:any, status:any, headers:any) => {
console.log('ImageUpload:uploaded:', item, status, response);
};
this.uploader.onCompleteAll = () => {
console.log('******* onCompleteAll *********')
}
this.uploader.onWhenAddingFileFailed = (item: any, filter: any, options: any) => {
console.log('***** onWhenAddingFileFailed ********')
}
}
}
Your HTML looks like this
<hello name="{{ name }}"></hello>
<p>Maximun allowed file size is 1MB</p>
<img [src]="thumb" *ngIf="ready"/>
<input type="file" ng2FileSelect [uploader]="uploader">
<button (click)="uploader.uploadAll()">Upload </button>

I got the solution ,
I have tested on your https://stackblitz.com/edit/angular-ng2-file-upload , try this it is working
export class AppComponent implements OnInit {
url = 'https://evening-anchorage-3159.herokuapp.com/api/';
uploader = new FileUploader({
url: this.url,
maxFileSize: 1024 * 1024 * 1
});
name = 'Angular 5';
//added this two variable here
imageUrlOfLogo:string='';
logoFileNameFile?: File;
ngOnInit() {
// your own code here
}
// added this code here
handleLogoFileInput(file: any) {
var item = file.item(0);
this.logoFileNameFile = file.item(0);
var reader = new FileReader();
reader.onload = (event: any) => {
this.imageUrlOfLogo = event.target.result;
}
reader.readAsDataURL(this.logoFileNameFile as File);
}
}
component.html
<p>Maximun allowed file size is 1MB</p>
<img [src]="imageUrlOfLogo" style="width:50%; height:90px;" *ngIf="logoFileNameFile">
<input type="file" ng2FileSelect [uploader]="uploader" (change)="handleLogoFileInput($event.target.files)">
<button (click)="uploader.uploadAll()">Upload </button>

Related

Cropping image with cropperJS at Angular it is not sending the cropped image in backend

So I am facing with an error which it doesn't send the cropped image to the backend with multer.
I can upload the file in frontend and then I crop the image but the cropped image is not sent in the backend, but it is the uploaded img sent to the backend.
I am using the cropper.js at Angular 11 version with a module that someone did develop for Angular.
this is the cropper.js https://fengyuanchen.github.io/cropperjs/
And this is the module https://github.com/matheusdavidson/angular-cropperjs
So my idea it is like this.
Upload photo -> crop it and save it in a folder at backend.
The save works but it saves the default img not the cropped img.
When user uses click event to saveImage , take the cropped image and save it in the backend.
This is my UI and methods.
<angular-cropper #angularCropper
[cropperOptions]="imgConfig"
[imageUrl]="imgUrl | safeurl"></angular-cropper>
<div class="btn-group">
<label class="btn btn-primary btn-upload" for="inputImage" title="Upload image file" >
<input type="file" class="sr-only" id="inputImage" name="file" accept="image/*" (change)="fileChangeEvent($event)">
<span class="docs-tooltip" data-toggle="tooltip" title="" data-original-title="Import image with Blob URLs">
<span class="fa fa-upload"></span>
</span>
</label>
</div>
<button type="button" class="btn btn-primary" data-method="crop" title="Crop" (click)="saveImage()">
<span class="docs-tooltip" data-toggle="tooltip" title="" data-original-title="cropper.crop()">
<span class="fa fa-check"></span>
</span>
</button>
TS file
imgUrl;
imageURL;
imageCrop;
#ViewChild("angularCropper", {static: false}) public angularCropper: CropperComponent;
public imgConfig = {
aspectRatio : 3/4,
dragMode : "move",
background : true,
movable: true,
rotatable : true,
scalable: true,
zoomable: true,
viewMode: 1,
checkImageOrigin : true,
checkCrossOrigin: true,
width: 0,
height: 0,
};
fileChangeEvent(event: any): void {
this.imgUrl = URL.createObjectURL(event.target.files[0]);
this.imageCrop = event.target.files[0];
}
saveImage() {
this.angularCropper.cropper.crop();
this.imageService.addImage(this.imageCrop).subscribe((res: any) => {
if (res.body) {
this.imageService.getImageByID(res.body._id).subscribe((t: Image) => {
this.imageURL = t.imageUrl;
console.log(this.imageURL);
});
}
}, (err: any) => {
console.log(err);
});
}
And this is my service
#Injectable({
providedIn: "root"
})
export class ImageService {
apiUrl = environment.backend;
constructor(private http: HttpClient) { }
addImage(file: File): Observable<any> {
const formData = new FormData();
formData.append("file", file);
const header = new HttpHeaders();
const params = new HttpParams();
const options = {
params,
reportProgress: true,
headers: header
};
const req = new HttpRequest("POST", `${this.apiUrl}/images/${file.name}`, formData, options);
return this.http.request(req);
}
getImageByID(id: string): Observable<any> {
const url = `${this.apiUrl}/${id}`;
return this.http.get<Image>(url).pipe(
catchError(this.handleError)
);
}
private handleError(error: HttpErrorResponse): any {
if (error.error instanceof ErrorEvent) {
console.error('An error occurred:', error.error.message);
} else {
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
return throwError(
'Something bad happened; please try again later.');
}
}
you will the cropped image from the output of cropper component.. export is the output name

Angular Shopping Cart App - Page needs to be refreshed for DOM to pick up changes

I am developing an online store for a client using Angular/Spring Boot. To keep things simple and to the point, I am storing the users shopping cart data in localStorage which is working fine. However, for the shopping cart to be updated with the users products, I have to refresh the page. I would like the app to just update without having to refresh the page. Im sure this is probably very trivial, but I cant get it to work!
I have tried looking at a few different sources :
Refreshing Page with Angular
Angular Source
I have tried using the this.router.routeReuseStrategy.shouldReuseRoute = function () { return false; }; within the components constructor but again didnt have any luck.
The main bits of code are as follows:
CartService - On construction we fetch the data from localStorage:
constructor(private http: HttpServiceService) {
this.getCartDetailsByUser();
}
getCartDetailsByUser() {
let data = JSON.parse(localStorage.getItem("products"));
this.cartObj = data;
if (data !== null) {
this.cartQty = data.length;
console.log(data);
}
}
When the user clicks "Add to Cart", this function is called, which adds the data to the local storage, but i need to update the DOM with whats in the cart and the cart length!
addCart(product) {
let products = [];
console.log(product);
if (localStorage.getItem("products")) {
products = JSON.parse(localStorage.getItem("products"));
}
products.push({
productId: product.productId,
image: product.image,
price: product.price,
});
localStorage.setItem("products", JSON.stringify(products));
}
I dont want to manually refresh the whole page for something so simple, I would just like the DOM to update with no need to refresh.
The header.component.html is what displays the shopping cart with its quantity etc
<div class="cart cart box_1 checkout-count-wrap">
<form action="#" method="post" class="last">
<button
class="w3view-cart"
type="submit"
(click)="openCheckoutModel()"
name="submit"
value=""
>
<p class="total_count_checkout">{{cart_qty}}</p>
<i class="fa fa-cart-arrow-down" aria-hidden="true"></i>
</button>
</form>
</div>
With the linked .ts class (header.component.ts). In the constructor, I get the qty which gets passed to the html above.
constructor(
private router: Router,
private cartService: CartServiceService,
private http: HttpServiceService
) {
this.cartService.cartServiceEvent.subscribe((data) => {
this.cart_qty = this.cartService.getQty();
});
}
When the user clicks on the shopping cart on the DOM, the following code is executed which gives a popup with the products etc in the cart:
openCheckoutModel() {
this.cartObj = this.cartService.getCartOBj();
this.cartTotalPrice = this.cartService.cartTotalPrice;
this.mainDialogType = "checkout";
}
Which in turn then displays the data in the shopping cart.
ALL of this works correctly apart from the cart not updating on the fly!!
Any help would be greatly appreciated!! :D
**** EDITED ANSWER ****
OK, so from the answer on the question, I have made a few small changes with the Observable pattern.. This half works - It updates the quantity of the cart on the fly (incrementing the number + 1 when a user clicks 'Add to Cart'). It also stores the product in the json object in localStorage as it did before. However, the actual items in the cart now do not show on the DOM, where as they did before. The data definitely exists with the correct products added being stored in localStorage, but now there seems to be some issues with the DOM displaying what's in it (productName, price etc)
Will this be due to another Observable being needed to track the item data in the cart? This may become clearer when I share my code (full classes)..
So here is the checkout-component.ts with the method being highlighted with *****
import { Component, OnInit } from "#angular/core";
import { CartServiceService } from "../service/cart-service.service";
import { HttpServiceService } from "../http-service.service";
import { Router } from "#angular/router";
#Component({
selector: "app-checkout",
templateUrl: "./checkout.component.html",
styleUrls: ["./checkout.component.css"],
})
export class CheckoutComponent implements OnInit {
cartObj = [];
cartTotalPrice: any;
pay_type = "cash_on_delivery";
delivery_address = "";
constructor(
private router: Router,
private cartService: CartServiceService,
private http: HttpServiceService
) {}
ngOnInit() {
this.getCartDetailsByUser();
//below function will be triggerd from when removing and qty is changing..
this.cartService.cartServiceEvent.subscribe((data) => {
this.cartObj = this.cartService.getCartOBj();
this.cartTotalPrice = this.cartService.cartTotalPrice;
});
}
qtyChange(qty, cartObj) {
var request = {
cartId: cartObj.id,
quantity: qty,
price: cartObj.price * qty,
};
this.http
.postRequestWithToken("api/addtocart/updateQtyForCart", request)
.subscribe(
(data: any) => {
this.cartService.getCartDetailsByUser(); //for updating in the application..
},
(error) => {
alert("Error while fetching the cart Details");
}
);
}
getCartDetailsByUser() {
let data = JSON.parse(localStorage.getItem("products"));
this.cartObj = data;
this.cartTotalPrice = this.getTotalAmounOfTheCart();
console.log("Cart Obj", this.cartObj);
console.log("Total", this.cartTotalPrice);
}
// getCartDetailsByUser(){
// this.http.postRequestWithToken("api/addtocart/getCartsByUserId",{}).subscribe((data:any)=>{
// this.cartObj = data;
// this.cartTotalPrice = this.getTotalAmounOfTheCart();
// },error=>{
// alert("Error while fetching the cart Details");
// })
// }
getTotalAmounOfTheCart() {
let obj = this.cartObj;
let totalPrice = 0;
for (var o in obj) {
totalPrice = totalPrice + parseFloat(obj[o].price);
}
return totalPrice.toFixed(2);
}
removeCartById(cartObj) {
if (confirm("Are you sure want to delete..?")) {
let id = cartObj.id;
this.cartService.removeCart(id);
}
}
checkoutCart() {
if (this.delivery_address == "") {
alert("Delivery address should not be empty");
return;
}
if (this.pay_type == "cash_on_delivery") {
let request = {
total_price: this.cartTotalPrice,
pay_type: "COD",
deliveryAddress: this.delivery_address,
};
this.http
.postRequestWithToken("api/order/checkout_order", request)
.subscribe(
(data: any) => {
alert("checkout process completed.Your Order is processed..");
this.cartService.getCartDetailsByUser();
this.router.navigate([""]);
},
(error) => {
alert("Error while fetching the cart Details");
}
);
} else {
alert("Payment Integration is not yet completed.");
}
}
}
Then the corresponding checkout-component.html
<div style="display: block;" id="w3lssbmincart">
<ul>
<li *ngFor="let cart of cartObj" class="sbmincart-item sbmincart-item-changed">
<div class="sbmincart-details-name">
<a class="sbmincart-name">{{cart.name}}</a>
</div>
<div class="sbmincart-details-quantity">
<select [(ngModel)]="cart.qty" (change)="qtyChange($event.target.value,cart)">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
</div>
<div class="sbmincart-details-remove">
<button (click)="removeCartById(cart)" type="button" class="sbmincart-remove" data-sbmincart-idx="0">×</button>
</div>
<div class="sbmincart-details-price">
<span class="sbmincart-price">{{cart.price}}</span>
</div>
</li>
</ul>
<div class="sbmincart-footer">
<div class="sbmincart-subtotal radio-wrap">
<span><input [(ngModel)]="pay_type" value="cash_on_delivery" type="radio" name="pay_type" /><span class="radio_text">Cash on Delivery</span></span>
<span><input [(ngModel)]="pay_type" value="online" name="pay_type" type="radio"/><span class="radio_text">Online</span></span>
</div>
<div class="sbmincart-subtotal">
<textarea placeholder="Enter the Delivery address" [(ngModel)]="delivery_address"></textarea>
</div>
<div class="sbmincart-subtotal">
Subtotal: <span class="price">${{cartTotalPrice}}</span>
</div>
<div>
<button (click)="checkoutCart()">Place Order</button>
</div>
</div>
<input type="hidden" name="bn" value="sbmincart_AddToCart_WPS_US">
</div>
</div>
</div>
</div>
Which simply loops over the cartObj stored within the service class.
I modified the header-component.ts (where the cart exists) to look like this:
import { Component, OnInit } from "#angular/core";
import { HttpServiceService } from "../http-service.service";
import { CartServiceService } from "../service/cart-service.service";
import { timingSafeEqual } from "crypto";
import { Router } from "#angular/router";
#Component({
selector: "app-header",
templateUrl: "./header.component.html",
styleUrls: ["./header.component.css"],
})
export class HeaderComponent implements OnInit {
isOpenLoginDialog = false;
currentDropDownMenu = "";
dialogType = "login";
mainDialogType = "";
isLogin = false;
mobile = "123456789";
password = "test";
cartObj = [];
cart_qty = 0;
cartTotalPrice = 0;
register = { name: "", email: "", mobile: "", password: "", re_password: "" };
welcomeUsername = "";
items$ = this.cartService.items$;
constructor(
private router: Router,
private cartService: CartServiceService,
private http: HttpServiceService
) {
let request = {};
this.http.postRequest("api/status", request).subscribe(
(data) => {
console.log("test", data);
},
(error) => {
alert("Server connection error " + error);
}
);
this.cartService.cartServiceEvent.subscribe((data) => {
this.cart_qty = this.cartService.getQty();
this.cartObj = this.cartService.getCartOBj();
});
}
logout() {
this.http.logout();
this.isLogin = false;
}
ngOnInit() {}
checkout_btn() {
this.router.navigate(["checkout"]);
}
openCheckoutModel() {
this.cartObj = this.cartService.getCartOBj();
this.cartTotalPrice = this.cartService.cartTotalPrice;
this.mainDialogType = "checkout";
}
openDialog() {
this.mainDialogType = "login";
}
dialogTypeInside(type) {
if (this.dialogType != type) this.dialogType = type;
}
closeDialog() {
this.mainDialogType = "";
}
curentDropDown(currentDropdownMenuName) {
if (this.currentDropDownMenu == currentDropdownMenuName) {
this.currentDropDownMenu = "";
} else {
this.currentDropDownMenu = currentDropdownMenuName;
}
}
}
Notice the openCheckoutModel() method which gets called which should pass the data down into the html component.
The data definitely exists as I am printing it out via console.log in the service class. The screen shot is below:
The front end DOM also shows there are 4 items in the cart:
However, the html does not display the actual data on the cart page:
From what I can see, i am looping over the data that definitely exists, however it does not show on the browser. I also get no errors :(
I hope this makes sense!
For peace of mind and for performance reasons, I would recommend you to go the RxJS way and turn things observable.
Short answer:
Here is a stackblitz example I could quickly make for you:
https://stackblitz.com/edit/angular-ivy-kgpicq
Long Answer:
I would recommend you structure your class as:
class CartService {
constructor() {
let cartItems = JSON.parse(localstorage.getItem('products'));
if (!cartItems) {
cartItems = []
}
this.itemsSubject.next(cartItems);
}
private itemsSubject = new BehaviorSubject<Product[]>([]);
items$ = itemsSubject.asObservable();
addToCart(item: Product) {
this.items$.pipe(
take(1),
map((products) => {
products.push(item);
localstorage.setItem('products', JSON.stringify(products));
},
).subscribe();
}
}
In your component class:
class ProductsPageComponent {
constructor(private cartService: CartService) {}
items$ = this.cartService.items$;
}
In your template:
<div class="cart cart box_1 checkout-count-wrap">
<form action="#" method="post" class="last">
<button class="w3view-cart" type="submit" (click)="openCheckoutModel()" name="submit" value="">
<p class="total_count_checkout">{{(items$ | async).length}}</p>
<i class="fa fa-cart-arrow-down" aria-hidden="true"></i>
</button>
</form>
</div>
AJAX
You can achieve this with ajax in plain javascript or with jQuery. My preference would go to jQuery.
Some code:
$.get( "/your_link", function( data ) {
$( ".result" ).html( data );
});
I would say you could write a another function in your controller that responds with the cart items. Then you could call the $.get whenever you would like to refresh your items. There's a lot of info on this so don't hesitate to look it up :)
https://api.jquery.com/jQuery.get/
Subscribe
Another solution might be to put a timeout on your subscribe. (this is some code from a project of mine which needed similar functionality to yours.)
In component.ts:
getUsers(): void {
// polling
timer(0, 2500)
.subscribe(() => {
this.userService.getUsers()
.subscribe(data => this.users = data);
});
}
In service.ts:
getUsers(): Observable<User[]> {
return this.http.get<User[]>(this.usersUrl);
}

object object error with java script and ionic

I create a mobile application with covid19 real time data. i have used api.but i can't access json data from it. when it runs object object error is showing.here is the current output
here is the data inside the api.here is the api data.
import { Component } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
import { LoadingController } from '#ionic/angular';
import { finalize } from 'rxjs/operators';
import { NULL_EXPR } from '#angular/compiler/src/output/output_ast';
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
data : string;
error: string;
loading: any;
obj: string;
updatedDateSL: string;
constructor(private http: HttpClient,public loadingController: LoadingController) {
this.data='';
this.error='';
this.obj='';
this.updatedDateSL='';
}
async ionViewWillEnter() {
await this.presentLoading();
// Load the data
this.prepareDataRequest()
.pipe(
finalize(async () => {
// Hide the loading spinner on success or error
await this.loading.dismiss();
})
)
.subscribe(
data=> { //data is a java script object that is why it can stringfy.
//updatedDateSL = data.data.update_date_time; // Set the data to display in the template
this.data = JSON.stringify(data); //converts to string
this.obj=JSON.parse(this.data); //info is a javascript objct
//var totCasesSL = info.data.local_total_cases;
//var totHospitalSL = data.local_total_number_of_individuals_in_hospitals;
//var totRecoverSL = data.local_recovered;
//var totDeathSL = data.local_deaths;
//var newSL = data.local_new_cases;
//var newDeathSL = data.local_new_deaths;
//var totActiveSL = data.local_active_cases;
//alert(info.update_date_time);
},
err => {
// Set the error information to display in the template
this.error = `An error occurred, the data could not be retrieved: Status: ${err.status}, Message: ${err.statusText}`;
}
);
}
async presentLoading() {
// Prepare a loading controller
this.loading = await this.loadingController.create({
message: 'Loading...'
});
// Present the loading controller
await this.loading.present();
}
private prepareDataRequest(): Observable<object> {
// Define the data URL
//const dataUrl = 'https://api.nigelbpeck.com/';
const dataUrl = 'https://hpb.health.gov.lk/api/get-current-statistical/';
// Prepare the request
return this.http.get(dataUrl);
}
}
here is the html file.
/<ion-header>
<ion-toolbar>
<ion-title>
Ionic 4 Example App
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<div class="ion-padding">
<p>Data will be presented here...</p>
<p *ngIf="!error;else errorContent">{{ obj ? obj : '-' }}</p>
<ng-template #errorContent><p><span style="color: red;">{{error}}</span></p></ng-template>
</div>
</ion-content>
i need to get local_new_cases and local_total_cases.Api connction is working here is the event that i run application sucessfly.final sucessful output.
To show data in html you need to stringify the data so you should use data instead of obj in html . Update html code from
<ion-content>
<div class="ion-padding">
<p>Data will be presented here...</p>
<p *ngIf="!error;else errorContent">{{ obj ? obj : '-' }}</p>
<ng-template #errorContent><p><span style="color: red;">{{error}}</span></p></ng-template>
</div>
</ion-content>
to
<ion-content>
<div class="ion-padding">
<p>Data will be presented here...</p>
<p *ngIf="!error;else errorContent">{{ data ? data : '-' }}</p>
<ng-template #errorContent><p><span style="color: red;">{{error}}</span></p></ng-template>
</div>
</ion-content>

How to enforce user to upload only specific file type in Angular

I want to enforce user to upload only pdf files in Angular 7 this is part of my code.When i click the button which is "Select File" at the page it brings "PDF File" but also brings "All Files" i want to enforce user by javascript function or typescript function help me please :)
Typescript
filesP2: File[] = [];
lastInvalidsP2: any;
sendableFormDataP2: FormData;
httpEmitter: Subscription;
httpEvent: HttpEvent<{}>;
maxSize: any;
lastFileAt: Date;
isBelgeVisible: boolean = false;
uploadedBelgeId: number = null;
HTML
<input style="margin: 0 auto;" ngfSelect type="file" [(files)]="filesP2" accept=".pdf" [maxSize]="maxSize" [(lastInvalids)]="lastInvalidsP2" (filesChange)="lastFileAt=getDate()"/>
<ngfFormData [files]="filesP2" postName="file" [(FormData)]="sendableFormDataP2"></ngfFormData>
If you are using reactive forms you can create custom validator
import {
FormControl
} from '#angular/forms';
export function requiredFileType(expectedFormats: string[]) {
return function(control: FormControl) {
const files = control.value;
if (files) {
const hasOtherType = files.some(file => {
const splitParts = file.name.split('.');
const extension = splitParts[splitParts.length - 1].toLowerCase();
return 'pdf' != extension.toLowerCase();
});
if (hasOtherType) {
return {
requiredFileType: 'Wrong file type. Only pdf type supported.'
};
}
}
return null;
};
}
//usage in angular forms
File: new FormControl({
value: null,
disabled: true
}, [Validators.required, requiredFileType(['xlsx', 'xlsm'])])

How to refresh an image with angular

I need to refresh an image that I load like this:
<img [src]="linkPicture" alt="profile photo" width="150px" height="150px">
Into the typescript file I have a variable this.linkPicture that I store initially the link. When I update the picture don't refresh. I set the variable again....
Here is part of my typescript code
public linkPicture : string;
Set the variable initially
this.service.GetProfile(id).subscribe(resp => {
.....
this.linkPicture = resp.Photo;
console.log(resp); //this show the photo
});
When I update the picture
let dialogRef = this.dialog.open(DialogUploadPhotoComponent, {
data: {
patientID: this.ss.getCurrentUserApi().PatientID
},
width : "550px",
});
dialogRef.afterClosed().subscribe(result => {
if(result != undefined){
console.log(result);
this.linkPicture = result; //I set the new picture.
}
});
You can append a timestamp query to the image URL to force the browser to reload the image. This shouldn't have any negative side effects with the server hosting the image.
Update the template to call a function:
<img [src]="getLinkPicture()" alt="profile photo" width="150px" height="150px">
Compute the URL using an optional timeStamp value:
public getLinkPicture() {
if(this.timeStamp) {
return this.linkPicture + '?' + this.timeStamp;
}
return this.linkPicture;
}
When the URL is changed. Create a new timeStamp value.
public setLinkPicture(url: string) {
this.linkPicture = url;
this.timeStamp = (new Date()).getTime();
}
Even if the URL is the same the timestamp changes, and this forces the browser to reload the image.
you can try like this. at least I solve liked this
on your .ts file
export class MainLayoutComponent implements OnInit {
public isDesktopDevice: boolean = true;
public sidebarBackgroundClass!: string;
public sideBarOpen: boolean = true; // *sidebar is open by default
}
ngOnInit(): void {
if (this.isDesktopDevice) { this.sidebarBackgroundClass = this.getLayoutBackground();
}
public getLayoutBackground(): string {
const bgs: string[] = [
'side1-1',
'side1-2',
'side2-1',
'side2-2',
];
const max = bgs.length;
const min = 0;
const index = Math.floor(Math.random() * (max - min)) + min;
const bgClass = bgs[index];
return bgClass;
then add photos to your css file one by one like this:
.css
.side1-1{ background-image: linear-gradient(rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.2)),url('/assets/images/side/side1.1.jpg') !important;}
the final add class to your html:
<mat-drawer [class]="sidebarBackgroundClass"></mat-drawer>
backgroundImageGenerate()
{
var myVar = setInterval(() => {
this.imageApi();
console.log(this.isStatusCode);
if (this.isStatusCode.indexOf(true) - 1) {
clearInterval(myVar);
}
}, 15000)
}
generateImage(){
this.campaignsService.generateImage(this.params.id).subscribe((response: any) => {
this.backgroundImageGenerate();
}, (error) => {
this.notify.error('Something went wrong');
console.log(error)
})
}
<button type="button" (click)="generateImage()" mat-raised-button color="primary"
[title]="'ADD_CAMPAIGN_PRODUCT' | translate:lang" style="margin:5px;">
<i class="material-icons">add_circle</i>{{ 'GENERATE_IMAGE' | translate:lang }}
</button>

Categories

Resources