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';
Related
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'
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
I'm trying to load json data via httpclient using get in Angular 5. I'm using a service, interface, component and json file; I've followed a few tutorials already to try and get this to work as well as verified my json with jsonlint. From what I can see, everything should function, the json should be parsed and everything should be fine except I get 'error: [object Object]' in the console every time. I've tried various things to fix it, such as
data => this.jsonArticles = Object.values(data);
this.articles = data[0];
but I can't get my data into any other form.
article.service.ts
import { Injectable } from '#angular/core';
import { Article } from './article';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class ArticleService {
// Variables
private _jsonUrl: string = './assets/data.json';
// Constructors
constructor(private http: HttpClient) { }
// Methods
getArticles(): Observable<Article[]> {
return this.http.get<Article[]>(this._jsonUrl);
}
}
article.component.ts
import { Component, OnInit } from '#angular/core';
import { ArticleService } from '../article.service';
import { Article } from '../article';
#Component({
selector: 'app-article',
templateUrl: './article.component.html',
styleUrls: ['./article.component.scss']
})
export class ArticleComponent implements OnInit {
// Variables
public jsonArticles = [];
public errorMsg;
// Consturctors
constructor(private _articleService: ArticleService) { }
// Methods
ngOnInit(){
this._articleService.getArticles()
.subscribe(
data => this.jsonArticles = data,
error => this.errorMsg = error);
}
}
article.ts
export interface Article {
id: number;
author: string;
title: string;
content: string;
tags: string[];
categories: string[];
publishDate: string;
published: boolean;
}
data.json
[
{
"id": 3,
"author": "",
"title": "Fancy Meat",
"content": "Strip steak bresaola capicola tail cow chicken corned beef turkey.",
"tags": ["test", "lorum"],
"categories": ["blah"],
"publishDate": "2018-02-12T08:15:00.000-05:00",
"published": true
},
]
I truncated the json file for brevity, there are more entries in the file making my json object an array and there is no comma after the last entry in the json array.
I got this error because I forgot to import HttpClientModule into app.module.ts and declare it into imports
...
import { HttpClientModule } from '#angular/common/http';
#NgModule({
declarations: [
...
],
imports: [
BrowserModule,
FormsModule,
AppRouteModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
I am trying to setup a mean stack crud application. The routes and the functionality is setup and tested using postman. I am getting correct responses for all the routes. Now I am trying to add the view part where the routes are called internally by the Angular application. I am trying to setup a basic get route. Following is my component code:
import { Component, OnInit } from '#angular/core';
import { UserService } from '../user.service';
#Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
users: {};
constructor(private userService: UserService) { }
ngOnInit() {
this.getUsers();
}
getUsers() {
this.userService.getAllUsers().subscribe(data => this.users = data);
}
}
and the service contains the following code:
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class UserService {
constructor(private http: Http) { }
getAllUsers() {
this.http.get('/api/users')
.map(res => res.json());
}
}
A sample response of the route using postman is as follows:
{
"status": true,
"err": null,
"data": [
{
"_id": "59d5db344c46e83a14b94616",
"name": "test"
},
{
"_id": "59d5db3c4c46e83a14b94617",
"name": "hello"
}
]
}
It always telling me the following error:
Property 'subscribe' does not exist on type 'void'.
What am I doing wrong? Can someone point me the standard way to do this?
Try this :
You forgot to return in your getAllUsers()
getAllUsers() {
return this.http.get('/api/users')
.map(res => res.json());
}
I am trying to pull data from a json file and display it, but I am unable to proceed with the program because I lack experience in coding Angular.
Currently using Angular 4.3, which uses HttpClientModule.
app.component.ts
import { Component, OnInit } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = '?';
data;
constructor(private http: HttpClient) {
}
ngOnInit(): void {
this.http.get('/src/app/students.json')
}
chgTab1() {
this.title = "Changed Title";
}
chgTab2() {
//Want to display the items from json file
}
}
students.json
[
{"id": "3", "mame": "Dama"},
{"id": "1", "mame": "ASD"},
{"id": "2", "mame": "Chris"},
{"id": "4", "mame": "Sass"},
]
import { Component, OnInit } from '#angular/core';
import { Http,Headers } from '#angular/http';
import 'rxjs/add/operator/map';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = '?';
data;
showData = false;
constructor(private http: Http) { }
ngOnInit(): void {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.get('/assets/students.json', { headers: headers }).map(res => res.json()).subscribe(data => {
this.data = data;
})
}
chgTab1(){
this.title ="Changed Title";
}
chgTab2(){
//Want to display the items from json file
this.showData = !this.showData;
}
}
I have edited the whole thing. It will now work for you. Ensure you have the path to your student.json in the correct place.I moved it to the assets directory