Unable to display image from database in angular2? - html

I am fetching the image URL from the database table and trying to show the image in tag but I am getting an error:-
Hide Copy Code
sanitizing unsafe URL value
if have used
Hide Copy Code
sanitizer.bypassSecurityTrustUrl()
After that the error has been removed but the image is still not been shown.
Here is my code of Component:-
import { Component, OnInit} from '#angular/core';
import { data } from '../Classes/edata';
import { dservice } from '../Service/dataservice';
import {DomSanitizer} from '#angular/platform-browser';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
})
export class HomeComponent implements OnInit {
emp:data[];
constructor(private _eservice:dservice , private sanitizer:DomSanitizer){}
public getSantizeUrl(url:string){
alert(url);
return this.sanitizer.bypassSecurityTrustUrl(url);
}
ngOnInit() {
this.load();
}
load(){
this._eservice.getdata().subscribe((edata)=>this.emp=edata);
}
}
class model:-
export class data
{
id:number;
name:string;
adress:string;
pic:string;
}
Html View:-
<div class="col-md-4 col-sm-6" *ngFor="let e of emp | paginate: {itemsPerPage:5, currentPage:p}">
<div class="property-card card">
<div class="property-card-header image-box">
<img src="{{e.pic}}">
What i tried
<img [src]="getSantizeUrl(e.pic)">

Related

Problem with My Wish List Items Showing Source unknown

I am having a problem showing my wish list items on the page. I'm using Angular 10 and json. Wen I click to add to favorites it color the heart and add it to to my json folder under wishlistitem, but when I route to page to look at the items no products are there. I can tell it hits the the *ngFor because the pipe for the dollar amount for each item appears but no images. When inspecting the source it shows src=unknown.
I have two folders wishlist-list and wishlistitem. I have a service for wishlistitem that is where I think my problem resides. I have included my code.
import { Component, OnInit, Input } from '#angular/core';
import {ProductService} from 'src/app/services/product.service'
import { MessengerService } from 'src/app/services/messenger.service';
import { WishlistService } from 'src/app/services/wishlist.service';
import { WishlistItemService } from '#app/services/wishlist-item.service';
import { Wish} from 'src/app/models/wish';
import {Product} from 'src/app/models/product';
#Component({
selector: 'app-wishlist-list',
templateUrl: './wishlist-list.component.html',
styleUrls: ['./wishlist-list.component.scss']
})
export class WishlistListComponent implements OnInit {
productList: Product[]= [];
wishlistItem: Wish[]= [];
wishItem = []
constructor( private msg: MessengerService,
private productService: ProductService,
private wishlistService: WishlistService,
private _wishlistitemService: WishlistItemService ) { }
ngOnInit(): void {
this.loadWishlistList();
}
loadWishlistList(){
this._wishlistitemService.getWishlistitem().subscribe((items: Wish[]) => {
this.wishItem= items;
this.msg.sendMsg("Is the item being captured" + items)
})
}
}
//Here is my Wishlist-list HTML
<p>wishlist-list works!</p>
<div class="container">
<div class="row">
<div class="col-md-2" *ngFor="let product of wishItem">
<app-wishlistitem [wishitemItem]="product"></app-wishlistitem>
</div>
</div>
</div>
//Here is my wishlist item service
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { wishlistitemUrl } from 'src/app/config/api';
import { map } from 'rxjs/operators';
import { ProductItemComponent } from '#app/shopping-cart/product-list/product-
item/product-item.component';
import { Observable, of } from 'rxjs';
import { catchError} from 'rxjs/operators';
import {Product} from 'src/app/models/product';
import {Wish} from 'src/app/models/wish';
#Injectable({
providedIn: 'root'
})
export class WishlistItemService {
product:any
wishlistitemUrl = 'http://localhost:3000/wishlistitem';
constructor(private http: HttpClient) { }
getWishlistitem(): Observable<Wish[]>{
return this.http.get<Wish[]>(wishlistitemUrl)
.pipe(
map((result: any[]) => {
let wishItem: Wish[]= [];
for(let item of result) {
let productExists = false
if (!productExists){
wishItem.push(new Wish(item.id, item.name, item.description,
item.price, item.imageUrl);
}
}
return wishItem;
})
);
}
addProductToWishlistItem(product:Wish):Observable<any>{
return this.http.post(wishlistitemUrl, {product});
}
}
//Here is wishlistitem
import { Component, Input, OnInit } from '#angular/core';
import { ProductService } from 'src/app/services/product.service'
import { WishlistService } from 'src/app/services/wishlist.service';
import { WishlistItemService } from '#app/services/wishlist-item.service';
import { MessengerService } from 'src/app/services/messenger.service';
import { map } from 'rxjs/operators';
import { Wish } from '#app/models/wish';
import { Product } from '#app/models/product';
#Component({
selector: 'app-wishlistitem',
templateUrl: './wishlistitem.component.html',
styleUrls: ['./wishlistitem.component.scss']
})
export class WishlistitemComponent implements OnInit {
#Input() wishitemItem: Wish
#Input() productItem: Product
#Input() product: string
constructor(private wishlistService: WishlistService, private _wishlistitemService:
WishlistItemService, private msg:MessengerService ) { }
ngOnInit(): void {
}
//This function works as expected
handleAddToWishlistitem(){
this._wishlistitemService.addProductToWishlistItem (this.wishitemItem).subscribe(()
=>{
alert("Get wish list item");
this.msg.sendMsg(this.wishitemItem)
})
}
}
//Here is wishlistitem Html
<p>wishlistitem works!</p>
<div class="test">
<div class="container" style="margin:0 auto">
<div class="row no-gutters" style="margin-top: 30px">
<div class="col-4">
<img class="shacker" [src]="wishitemItem.imageUrl" />
<div class="card-body">
<p class="card-text" style="text-align:left; width:130px">
{{wishitemItem.name}}</p>
<p class="card-text" style="text-align:left; width:130px;">
<strong>{{ wishitemItem.price | currency }}</strong>
</p>
<p class="card-text" style="text-align:left; width: 150px">
{{wishitemItem.description | slice: 0:20}}...</p>
</div>
</div>
</div>
</div>
</div>
//I hope the explanation is sufficient. I have tried many scenarios, the issue I'm
having is with the property for the wishlist item, carItem does not have a property
and when I create one the application doesn't behave as expected.
Thank you in advance
PDH

I am getting this error TS2322: Type 'Category' is not assignable to type 'NgIterable<any> | null | undefined'

I worked on my code a lot but could not debug it ngFor works for other arrays but it is not working for this specific array.categoryList is an array but its not working in ngFor loop in DOM
kindly solve this problem.
Thanks in advance
This is my ts file
import { ActivatedRoute } from '#angular/router';
import { Category } from './../category';
import { ProductserveService } from './../../../productserve.service';
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-products',
templateUrl: './products.component.html',
styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {
categoryList!:Category
userLoaded = false;
constructor(private productService:ProductserveService){ }
ngOnInit(): void {
this.productService.getCategories().subscribe(data=>{
this.userLoaded=true;
console.log("Courses data",this.courses)
console.log("Incoming data: ",data);
this.categoryList=data;
this.userLoaded = true;
// debugger
});
}
}
This is the interface file
export interface Category{
id:number
categoryName:any;
}
This is my Html Code
<div class="list-group m-auto" *ngIf="userLoaded===true">
<a *ngFor="let cat of categoryList" class="list-group-item" href="#" >
<p>{{cat.categoryName}}</p>
</a>
</div>

How to make an HTTP request on page load in Angular (works with a button)

I am trying to make an HTTP request to an API when my page loads and have the text of the response display on the screen. I am using Angular framework.
I currently have it working as I desire when you press a button. I want the exact functionality I have with the button, but for it to happen automatically on page load.
//TypeScript
import { Component, OnInit } from '#angular/core';
import { Observable, Subscription } from 'rxjs';
import { HttpClient, HttpParams, HttpHeaders } from '#angular/common/http';
#Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
posts: Observable<String[]>;
constructor(private http:HttpClient) {
}
public getPosts() {
this.posts = this.http.get<any[]>('https://jsonplaceholder.typicode.com/posts');
}
ngOnInit() {
}
}
HTML
<button (click) = "getPosts()">GetPosts</button>
<div *ngFor="let post of posts | async">
Name
{{post | json}}
</div>
This gives me a page with a button. When I press the button I get the information from the API. I want the API to give me the information right away when the page is loaded.
Just Invoke the method on ngOnInit
ngOnInit() {
this.getPosts()
}
or You can do like below also
export class ProfileComponent implements OnInit {
posts: Observable<String[]> = this.http.get<any[]>('https://jsonplaceholder.typicode.com/posts');
constructor(private http:HttpClient) {
}
}

Angular and Typescript Sending Post Request

I have a simple page with angular and typescript with just 1 button and 1 text field. I want to make a post request to a link that posts the string written in text box.
my button html:
<a class="button-size">
Add Customer
</a>
and button ts file:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'customer-button123',
templateUrl: './blabla',
styleUrls: ['./clacla']
})
export class AddCustomerButtonComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
text box html:
<mat-form-field>
<input matInput placeholder="Customer Name">
</mat-form-field>
text box ts file:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'customer-text-field',
templateUrl: './blabla2',
styleUrls: ['./clacla2']
})
export class CustomerTextFieldComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
and simple wrapper page html is:
<div class="input-label">
<mg-customer-text-field></mg-customer-text-field>
</div>
<div>
<mg-customer-button123></mg-customer-button123>
</div>
How can i send a post reques to link localhost8080/admin/addCustomer ?
If you hosting your front end at port: 4200 (default Angular port serve) and you want to send a request to http://localhost8080/admin/addCustomer, you will need a proxy configuration. You can see right here for more info: https://itnext.io/angular-cli-proxy-configuration-4311acec9d6f
You use the HttpModule
I use a service to separate http requests.
Example
import { Component, OnInit } from '#angular/core';
import { ApiService } from '../../services/api.service';
#Component({
selector: 'customer-button123',
templateUrl: './blabla',
styleUrls: ['./clacla']
})
export class AddCustomerButtonComponent implements OnInit {
data: any;
results: any;
constructor(private apiService: ApiService) { }
ngOnInit() {
}
getDataFromApi() {
this.apiService.getData(this.data).subscribe(results => {
this.results = results;
});
}
ApiService
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class ApiService {
apiUrl: string = environment.apiUrl;
constructor(private http: HttpClient) {}
getData(data): any {
return this.http.get(`http://localhost:8080/api/get-data`);
}
html
<div class="input-label">
<mg-customer-text-field [(ngModel)]="data"></mg-customer-text-field>
</div>
<div>
<mg-customer-button123 (click)="getDataFromApi()"></mg-customer-button123>
</div>

Angular 5 add dynamic html file into DIV

I am very new to Angular, I am trying to insert the html file as my string and insert into DIV element
I have my search.component.html called
<div #ID></div>
components.ts
import { Component} from '#angular/core';
#Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.scss']
})
export class SearchComponent {
constructor() {}
let ServerResponseHtml = '<div><input type="text"/><input type="text"/><span class="btn btn-outline-primary btn-sm" (click)="open(content)">View Document</span></div>';
document.getElementById("DIV").innerHTML = ServerResponseHtml;
}
I am getting the response from server as complete html markup, Just I need to append into my DOM and display the content, the markup can have inline styles also.
I tried for <div [innerHTML]="ServerResponseHtml"></div> and <div innerHTML="{{ServerResponseHtml}}"></div> but this is not displaying as html it is displayed as text.
We need to use the safehtml for displaying the html.
We need to create the Pipe for this. safe-html-pipe.ts
import {DomSanitizer, SafeHtml} from '#angular/platform-browser';
import {Pipe, PipeTransform} from '#angular/core';
#Pipe({name: 'safehtml'})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {
}
transform(value): SafeHtml {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
component.ts
We need to import the pipe
import {Component, NgModule, Pipe, PipeTransform} from '#angular/core'
import {BrowserModule} from '#angular/platform-browser'
import { FormsModule } from '#angular/forms';
import { DomSanitizer } from '#angular/platform-browser'
import { SafeHtmlPipe } from './safe-html-pipe';
#Component({
selector: 'app-root',
template:
`<div [innerHtml]="safeHtmlContent | safehtml">
</div>"})`
export class AppComponent {
name:string;
safeHtmlContent : string;
constructor() {
this.name = 'Angular2'
this.safeHtmlContent = '<html><head><title>Hello safe</title></head><body><h1>hello world Hello Umesh</h1></body></html>';
}
}
Hope this helps :).