Get SVG from http GET method and display it - html

I'm trying to display a SVG image in my webapp but I don't own the SVG as a file "image.svg", I call my service and it responds with a http response. The response is as below :
"headers": {
"access-control-allow-methods": [
"PUT"
],
"content-length": [
"249664"
],
"x-powered-by": [
"Express"
],
"content-disposition": [
"attachment; filename=out.svg"
],
"etag": [
"W/\"3cf40-pgVjFGaVCiK8oIvC+f36ew7CrB8\""
],
"access-control-allow-headers": [
"Content-Type, Authorisation"
],
"connection": [
"keep-alive"
],
"access-control-allow-origin": [
"*"
],
"date": [
"Fri, 22 Nov 2019 14:06:47 GMT"
],
"content-type": [
"text/html; charset=utf-8"
]
},
"body": "PHN2ZyB4bWxucz0iaHR0cDovL3 [...] 5lPjwvc3ZnPg=="
I already try to use an object tag with the [data] attribute and passing the content of the body in that [data] field, but the result is not as excepted (it's my webapp but in a litle window... I don't understand)
Is there a way to display that SVG without downloading it as a file ?

You need to use DomSanitizer for sanitizing your base64 image. Import DomSanitizer and use in HTML as follows,
TS
import { Component } from '#angular/core';
import { DomSanitizer } from '#angular/platform-browser';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
// variable containing image string (base64)
// in your case body of response
svgData = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
constructor(public sanitizer: DomSanitizer) { } // inject domsanitizer
}
HTML
<img [src]="sanitizer.bypassSecurityTrustResourceUrl('data:image/svg+xml;base64, '+ svgData)">
Demo Stackblitz

Related

How do I solve parsing error, cannot read file 'tsconfig.json' in an ionic project with Angular Framework?

I'm currently try to make a ReactiveForms with ionic angular Framework, but for some reason it always says parsing error, cannot read file tsconfig.json. here is the code:
app.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss'],
})
export class AppComponent {
public appPages = [
{ title: 'Login', url: '/login', icon: 'log-in' },
{ title: 'Register', url: '/register', icon: 'albums' },
];
public labels = ['Firebase'];
constructor() {}
}
.eslintrc.json
{
"root": true,
"ignorePatterns": ["projects/**/*"],
"overrides": [
{
"files": ["*.ts"],
"parserOptions": {
"project": ["./tsconfig.json"],
"createDefaultProgram": true
},
"extends": [
"plugin:#angular-eslint/recommended",
"plugin:#angular-eslint/template/process-inline-templates"
],
"rules": {
"#angular-eslint/component-class-suffix": [
"error",
{
"suffixes": ["Page", "Component"]
}
],
"#angular-eslint/component-selector": [
"error",
{
"type": "element",
"prefix": "app",
"style": "kebab-case"
}
],
"#angular-eslint/directive-selector": [
"error",
{
"type": "attribute",
"prefix": "app",
"style": "camelCase"
}
]
}
}
,
{
"files": ["*.html"],
"extends": ["plugin:#angular-eslint/template/recommended"],
"rules": {}
}
]
}
I tried to create a settings.json in .vscode folder, but nothing happened the error is still displayed.
settings.json
{
"eslint.workingDirectories": [
"src"
]
}

Angular Response error : SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse

I want get my data from an API. The API itself works fine in postmap like this :
{
"status": "Success",
"data": [
{
"title": "asus g551 vw",
"price": 500,
"image": "https://localhost:44345/images/products/origin/img1.jpg",
"count": 2
},
{
"title": "asus vivobook",
"price": 1200,
"image": "https://localhost:44345/images/products/origin/img1.jpg",
"count": 2
},
{
"title": "acer predator",
"price": 200,
"image": "https://localhost:44345/images/products/origin/img1.jpg",
"count": 1
}
]
}
But in Angular, when I call my get function, I get an error from this Angular code :
myservice method 'GetUserBasketDetails()' :
#Injectable({
providedIn: 'root'
})
export class OrderService {
private orderDetails : BehaviorSubject<OrderBasketDto[]> = new BehaviorSubject<OrderBasketDto[]>(null);
constructor(private _http : HttpClient) { }
_SetOrderDetails(details : OrderBasketDto[]){
this.orderDetails.next(details);
console.log(this.orderDetails)
}
_GetOrderDetails() : Observable<OrderBasketDto[]>{
return this.orderDetails;
}
GetUserBasketDetails():Observable<IResponseResult<OrderBasketDto[]>>{
return this._http.get<IResponseResult<OrderBasketDto[]>>('/basket-details');
}
}
when I call it in a component :
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
title = 'Front-Project';
constructor(private _accountService : AccountService,
private _orderService : OrderService) {
}
ngOnInit():void {
this._orderService.GetUserBasketDetails().subscribe(res=>{
console.log(res)
})
}
}
This is the error I get:
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "https://localhost:44345/basket-details", ok: false, …}
and
Error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:20175:51) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:10720:31)
in console
console error image
How can I fix this?
I found th problem my url was wrong i forgot to add api controller name in get method
like this '/order/basket-details'

How can I access the json key value with help of typescript variable?

Json File
"Tamil": {
"Name": "பெயர்",
"Email": "மின்னஞ்சல்",
"Phoneno": "தொலைபேசி எண்",
"Password": "கடவுச்சொல்",
"CPassword": "கடவுச்சொல்லை உறுதிப்படுத்தவும்",
"Register": "பதிவு",
"Cancel": "ரத்துசெய்"
},
Ts File
import {Component, OnInit} from '#angular/core';
import * as data from '../home/lang.json';
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
public language;
public value;
constructor() {
this.value = 'Tamil';
this.language = data[this.value].Name;
alert(this.language);
}
ngOnInit() {
}
}
Output
ERROR Error: "Uncaught (in promise): TypeError: _home_lang_json__WEBPACK_IMPORTED_MODULE_2___namespace[this.value] is undefined
HomePage#http://localhost:8100/home-home-module.js:128:9
HomePage_Factory#ng:///HomePage/ɵfac.js:5:10
But When I try this possibility is working fine:
this.language = data["Tamil"].Name;
But while trying this
this.language = data[this.value].Name;
It's Showing that error.
The only mistake you are doing is accessing Malayalam which does not exist in your JSON file, add Malayalam and it will work fine.
Some code fine tune I am doing which might help.
replace
import * as data from '../home/lang.json'
to coz TypeScript > 2.9 has a simplest way to do that
import data from '../home/lang.json
JSON File
{
"Tamil": {
"Name": "பெயர்",
"Email": "மின்னஞ்சல்",
"Phoneno": "தொலைபேசி எண்" ,
"Password": "கடவுச்சொல்",
"CPassword": "கடவுச்சொல்லை உறுதிப்படுத்தவும்",
"Register":"பதிவு",
"Cancel" : "ரத்துசெய்"
},
"Malayalam": {
"Name": "பெயர் m",
"Email": "மின்னஞ்சல் m",
"Phoneno": "தொலைபேசி எண் m" ,
"Password": "கடவுச்சொல் m",
"CPassword": "கடவுச்சொல்லை உறுதிப்படுத்தவும் m",
"Register":"பதிவு m",
"Cancel" : "ரத்துசெய் m"
}
}
Component
constructor() {
this.value = "Malayalam";
this.language = data[this.value].Name;
alert(this.language)
}
Hope this works.
The dynamic import returns Promise.
use case:
import * as data from '../home/lang.json'
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
public language;
public value;
constructor() {
this.value = "Malayalam";
this.language = data.default <=== add `default`
[this.value]?.Name;
alert(this.language)
}
ngOnInit() {
}
}
You can print data in the console to see its structure.
You can make on http call to fetch the json data
constructor(
private httpClient: HttpClient
) { }
this.httpClient.get('../home/lang.json')
.subscribe((res) => {
this.data = res;
});
Or simply you can read the file as
this.data= require('../home/lang.json');
CheckThis
You can the value by
this.result =this.data[this.language].Name
Sample code
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template:
`<input [(ngModel)]="language" (ngModelChange)="onSelection()" >
<h1>{{ result ? result : data[language].Name }}</h1>`,
})
export class AppComponent {
language = 'Tamil';
result='';
public data = {
"Tamil": {
"Name": "பெயர்",
"Email": "மின்னஞ்சல்",
"Phoneno": "தொலைபேசி எண்" ,
"Password": "கடவுச்சொல்",
"CPassword": "கடவுச்சொல்லை உறுதிப்படுத்தவும்",
"Register":"பதிவு",
"Cancel" : "ரத்துசெய்"
} ,
"Malayalam": {
"Name": "Name Malayalam",
"Email": "Email malayalam",
"Phoneno": "தொலைபேசி எண்" ,
"Password": "கடவுச்சொல்",
"CPassword": "கடவுச்சொல்லை உறுதிப்படுத்தவும்",
"Register":"பதிவு",
"Cancel" : "ரத்துசெய்"
}
}
onSelection() {
this.result =this.data[this.language].Name
}
}
I think you forgot to add Malayalam language in your json.
If it can be happen that language may not present in your json then you should do like this
this.language = data[this.value] ? data[this.value].Name : '';
Instead of blank you can use default language too. If defualt language available in your json file then you can use like this.
this.language = data[this.value] ? data[this.value].Name : data['defaultLanguage'].Name ;

Unable to Parse JSON data in angular requested through API

I am trying to get the data of movie from imdb site with the help of an API but unable to process the data further.
Here is the link i pass ("https://sg.media-imdb.com/suggests/j/johnwick.json") in the get method and opening the browser it looks like this:
imdb$johnwick({
"v": 1,
"q": "johnwick",
"d": [
{
"l": "John Wick: Chapter 3 - Parabellum",
"id": "tt6146586",
"s": "Keanu Reeves, Ian McShane",
"y": 2019,
"q": "feature",
"vt": 5,
"i": [
"https://m.media-amazon.com/images/M/MV5BNDU3YzJlY2EtODA3NS00ZWM3LWJhYjUtZWE3MmE2YmEzNWYwXkEyXkFqcGdeQXVyNDMzMzI5MjM#._V1_.jpg",
4050,
6000
],
"v": [
{
"l": "Official Trailer",
"id": "vi3978017305",
"s": "2:18",
"i": [
"https://m.media-amazon.com/images/M/MV5BNTg2YzEyNjktMmRmZi00NjU4LWIxNzYtMGE0Y2U2MDI5Y2Q1XkEyXkFqcGdeQW1yb3NzZXI#._V1_.jpg",
1920,
1080
]
}
]
},
{
"l": "John Wick",
"id": "tt2911666",
"s": "Keanu Reeves, Michael Nyqvist",
"y": 2014,
"q": "feature",
"vt": 23,
"i": [
"https://m.media-amazon.com/images/M/MV5BMTU2NjA1ODgzMF5BMl5BanBnXkFtZTgwMTM2MTI4MjE#._V1_.jpg",
1365,
2048
],
"v": [
{
"l": "Trailer #2",
"id": "vi2273816345",
"s": "1:00",
"i": [
"https://m.media-amazon.com/images/M/MV5BMjU0OTQwMjUyN15BMl5BanBnXkFtZTgwODQ5OTE4MjE#._V1_.jpg",
640,
480
]
},
{
"l": "Clip",
"id": "vi3905924889",
"s": "0:29",
"i": [
"https://m.media-amazon.com/images/M/MV5BNDYwMTUwNTMyNF5BMl5BanBnXkFtZTgwNDcyMjExMzE#._V1_.jpg",
1280,
720
]
},
{
"l": "John Wick",
"id": "vi2809377049",
"s": "4:18",
"i": [
"https://m.media-amazon.com/images/M/MV5BNGQ1YjYwOTUtODRkOS00NjU3LWJjZTMtOWM1MWE2YmFiN2ZjXkEyXkFqcGdeQXVyNzU1NzE3NTg#._V1_.jpg",
480,
360
]
}
]
},
{
"l": "John Wick: Chapter 2",
"id": "tt4425200",
"s": "Keanu Reeves, Riccardo Scamarcio",
"y": 2017,
"q": "feature",
"i": [
"https://m.media-amazon.com/images/M/MV5BMjE2NDkxNTY2M15BMl5BanBnXkFtZTgwMDc2NzE0MTI#._V1_.jpg",
1328,
2048
]
},
{
"l": "John Williams",
"id": "nm0002354",
"s": "Music Department, Star Wars: Episode I - The Phantom Menace (1999)",
"i": [
"https://m.media-amazon.com/images/M/MV5BMjY5MTgzMTQ1NF5BMl5BanBnXkFtZTYwNDg3OTcz._V1_.jpg",
280,
400
]
},
{
"l": "John Witherspoon",
"id": "nm0936762",
"s": "Actor, Friday (1995)",
"i": [
"https://m.media-amazon.com/images/M/MV5BMTM2NTg4MDcxNV5BMl5BanBnXkFtZTYwMDAxMzY0._V1_.jpg",
317,
400
]
},
{
"l": "John Williams",
"id": "nm0002369",
"s": "Actor, Sabrina (1954)",
"i": [
"https://m.media-amazon.com/images/M/MV5BMTUyNDg1MTU5MV5BMl5BanBnXkFtZTcwMTgwNTUxOA##._V1_.jpg",
1107,
1426
]
},
{
"l": "John Wilder",
"id": "nm0928588",
"s": "Writer, Centennial (1978-1979)",
"i": [
"https://m.media-amazon.com/images/M/MV5BMjAxNjE0NzE1MV5BMl5BanBnXkFtZTcwNzUzNjI0NA##._V1_.jpg",
473,
650
]
},
{
"l": "John Wick Chapter 2: Wick-vizzed",
"id": "tt7161870",
"s": "Pedro Hollywood, J.J. Perry",
"y": 2017,
"q": "video",
"i": [
"https://m.media-amazon.com/images/M/MV5BNDNkZDI0MjktMmZiYS00ZjI4LWI3ZDctMTBhMTMyYjczMDhlXkEyXkFqcGdeQXVyODA1NjQ0OTY#._V1_.jpg",
2000,
3000
]
}
]
})
Here is my angular code (The service file):
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class MovieProviderService {
storeMovie: any[];
constructor(private http: HttpClient) { }
getmovies(): Observable<any>
{
return this.http.get('https://sg.media-imdb.com/suggests/j/johnwick.json');
}
}
The below code is the file getting served:
import { Component, OnInit } from '#angular/core';
import { MovieProviderService } from '../movie-provider.service';
#Component({
selector: 'app-movie-container',
templateUrl: './movie-container.component.html',
styleUrls: ['./movie-container.component.scss']
})
export class MovieContainerComponent implements OnInit {
constructor(private movieService: MovieProviderService) { }
ngOnInit() {
let obs = this.movieService.getmovies();
obs.subscribe(
(response)=>{
const data = response.json();
console.log(data);},
(error)=>{console.log(error)}
)
}
}
It is giving the parsing error on console of chrome like unable to parse JSON at position 0...
I can see that the JSON data is contained inside imdb$johnwick( JSON ). How to get rid of that or may be tell some other good way or some topics which i need to learn. THANKYOU
IMDB return data in JSONP format so here you need to import HttpClientModule and HttpClientJsonpModule into your module.
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
// Import relevant http modules
import { HttpClientModule, HttpClientJsonpModule } from '#angular/common/http';
import { AppComponent } from './app.component';
import { ExampleService } from './example.service';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
// Import relevant http modules
HttpClientModule,
HttpClientJsonpModule
],
providers: [ExampleService],
bootstrap: [AppComponent]
})
export class AppModule { }
model-provider.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class MovieProviderService {
storeMovie: any[];
constructor(private http: HttpClient) { }
getmovies(): Observable<any>
{
return this.http.jsonp('https://sg.media-imdb.com/suggests/j/johnwick.json', 'callback');
}
}
Hope this will help!
In the service.js pass the option to handle the response as "text". We want to handle the reformatting of the text response in the service so we do not need to account for this in every component.
Using /(?:^.*?(\{)|\)$)/gm replaces everything before the first { and the ending ). The gm is "global" and "multi-line" for matching and will only replace the text if these rules are matched. We will then replace with first capture group of the RegExp (if there is no capture group one $1 becomes a blank string).
I took this approach to ensure if the source passes valid JSON in the future we wont be breaking/replacing valid JSON.
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class MovieProviderService {
storeMovie: any[];
constructor(private http: HttpClient) { }
getmovies(): Observable<string>
{
return this.http.get('https://sg.media-imdb.com/suggests/j/johnwick.json', { responseType: 'text' })
.map((res) => {
return JSON.parse(res.replace(/(?:^.*?(\{)|\)$)/gm, "$1"));
});
}
}
import { Component, OnInit } from '#angular/core';
import { MovieProviderService } from '../movie-provider.service';
#Component({
selector: 'app-movie-container',
templateUrl: './movie-container.component.html',
styleUrls: ['./movie-container.component.scss']
})
export class MovieContainerComponent implements OnInit {
constructor(private movieService: MovieProviderService) { }
ngOnInit() {
let obs = this.movieService.getmovies();
obs.subscribe(
(response)=>{
const data = response; // no longer need to call .json()
console.log(data);},
(error)=>{console.log(error)}
)
}
}

Angular 6 post prefixing http://localhost:4200/

I am trying to post a JSON file to a RESTful endpoint, but the request always prefixes "http://localhost:4200" to it.
Code:
app.component.ts
import {Component } from '#angular/core';
import {HttpClient} from '#angular/common/http';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: './app.component.css'
})
export class AppComponent {
private _url = 'website.com';
private _url2 = './assets/data/rfdata2.json';
public newGet = this.http.post(this._url, this._url2);
constructor(private http: HttpClient) {
this.newGet.subscribe(data => this.getArray = data);
}
}
./assets/data/rfdata2.json
[
{"frequency":2440.000, "name": "sig1", "id": "{mf0382mf4q8392-28nm3fq- q2u389mqf}"},
{"frequency":2460.000, "name": "sig2", "id": "{39n893-48398anjh9n8na-0398wnf}"},
{"frequency":2480.000, "name": "sig3", "id": "{fanb8903y84-may7md9a387kfa7m8}"}
]
Error text
ERROR Object { headers: Object, status: 404, statusText: "Not Found", url: "http://localhost:4200/website.com", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://we…", error: "<!DOCTYPE html> <html lang="en"> <h…" }
(Obviously, website.com isn't the real endpoint. Just using it as a placeholder for my real website)
I also get the same error with a GET request. How do I get it to NOT prefix "http://localhost:4200/" to the POST URL?
Add a protocol to your URL.
private _url = 'https://website.com';