ERROR TypeError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': Value is not a valid ByteString - angular9

I create an application using Node.js and Angular9.
It is used to allow anyone to establish a company on the site. When an employee comes to create a
company, he presses on the site "create a company" and a form appears to put the company name,
address and domain for it, and when he presses the "create" button, this problem appears.
Knowing that the backend is NodeJs.
And when I create a company using Postman I don't have any problems.
The problem is only on the part of the Angular.
when I execute the code from the Angular side, I have this problem:
ERROR TypeError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': Value is not a valid ByteString
and this Error:
ERROR CONTEXT
This is the Code:
Company.server.ts:
import { Injectable } from '#angular/core';
#Injectable()
export class CompanyService {
constructor() { }
}
Company.server.spec.ts:
import { TestBed, inject } from '#angular/core/testing';
import { CompanyService } from './company.service';
describe('CompanyService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [CompanyService]
});
});
it('should be created', inject([CompanyService], (service: CompanyService) => {
expect(service).toBeTruthy();
}));
});
data.service.ts:
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpParams, HttpHeaders } from '#angular/common/http';
import { platformBrowserDynamicTesting } from '#angular/platform-browser-dynamic/testing';
import { BoundDirectivePropertyAst } from '#angular/compiler';
#Injectable()
export class DataService {
constructor(private httpClient: HttpClient) { }
create_company(body): Observable<any> {
var reqHeader = new HttpHeaders({
'Authorization': localStorage.getItem('token'),
'Content-Type': 'application/json'
});
return this.httpClient.post<any>
('http://localhost:3001/employee/company', body, { headers: reqHeader });
}
Company.component.ts:
import { Component, OnInit } from '#angular/core';
import { Router } from "#angular/router"
import { DataService } from '../../_services/data.service';
#Component({
selector: 'app-company',
templateUrl: './company.component.html',
styleUrls: ['./company.component.css']
})
export class CompanyComponent implements OnInit {
newCompany = {
company: {
name: '',
address: '',
domain: ''
}
}
public id: string;
public name: string;
public roles: any;
public email: string;
public token: string;
constructor(private dataService: DataService, private router: Router) { }
createCompany() {
console.log(JSON.stringify(this.newCompany));
console.log(localStorage.getItem('token'));
this.dataService.create_company(JSON.stringify(this.newCompany)).subscribe((data) => {
console.log(data);
})
}
logout() {
localStorage.clear();
this.router.navigate(['/register']);
}
ngOnInit() {
this.roles = localStorage.getItem('roles');
console.log(this.roles);
this.id = localStorage.getItem('id');
this.name = localStorage.getItem('name');
this.email = localStorage.getItem('email');
this.token = localStorage.getItem('token');
localStorage.setItem('id', "14ll06y4kbne6x6g");
localStorage.setItem('name', "Dalida");
localStorage.setItem('email', "dalida#gmail.com");
localStorage.setItem('roles', JSON.stringify([
{
roleId: 3,
targetId: '0',
employeeId: '14ll08o4kbm7apn9'
},
{
roleId: 2,
targetId: '4',
employeeId: '14ll08o4kbm7apn9'
}
]));
localStorage.setItem('token', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjE0b…
I2MH0.wHUoGDYqZIsty1DqUxUtkuQReBUidS4mC0MAQi1bMtQ');
}
}
How can I solve this problem?

Related

Type 'Data' is missing the following properties from type

I'm new to Angular 8 and wondering why im getting this error, also if you see a better way to write the following code please don't hesitate to give me tips.
Type 'Data' is missing the following properties from type 'Documentary': id, > title, slug, storyline, and 13 more.
The error is here in AdminDocumentaryEditComponent
ngOnInit() {
this.route.data.subscribe(data => {
this.documentary = data; //here
console.log(this.documentary);
this.initForm();
})
}
DataService
import { HttpClient, HttpParams } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
#Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private url: string, private http: HttpClient) { }
get(slug) {
return this.http.get(this.url + '/' + slug);
}
getAll(params:HttpParams) {
return this.http.get<Object[]>(this.url,
{
params: params
});
}
create(resource) {
return this.http.post(this.url, JSON.stringify(resource));
}
update(resource) {
return this.http.put(this.url + '/' + resource.id, JSON.stringify({
}));
}
delete(id: number) {
return this.http.delete(this.url + '/' + id);
}
}
DocumentaryService
import { HttpClient } from '#angular/common/http';
import { DataService } from './data.service';
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root'
})
export class DocumentaryService extends DataService {
constructor(http: HttpClient) {
super('http://localhost:8000/api/v1/documentary', http);
}
}
DocumentaryResolverService
import { Documentary } from './../models/documentary.model';
import { DocumentaryService } from './documentary.service';
import { Injectable } from '#angular/core';
import {
Resolve,
ActivatedRouteSnapshot,
RouterStateSnapshot
} from '#angular/router';
#Injectable({ providedIn: 'root' })
export class DocumentaryResolverService implements Resolve<Documentary> {
constructor(private documentaryService: DocumentaryService) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
let slug = route.params['slug'];
let documentary = this.documentaryService.get(slug)[0];
return Object.assign(new Documentary(), documentary);
}
}
AdminDocumentaryEditComponent
import { Documentary } from './../../../models/documentary.model';
import { DocumentaryService } from './../../../services/documentary.service';
import { Params, ActivatedRoute, Router } from '#angular/router';
import { Component, OnInit, ViewChild, ChangeDetectorRef } from '#angular/core';
import { FormArray, FormControl, FormGroup, Validators } from '#angular/forms';
import { AngularEditorConfig } from '#kolkov/angular-editor';
#Component({
selector: 'app-admin-documentary-edit',
templateUrl: './admin-documentary-edit.component.html',
styleUrls: ['./admin-documentary-edit.component.css']
})
export class AdminDocumentaryEditComponent implements OnInit {
documentary: Documentary;
editDocumentaryForm: FormGroup;
constructor(
private route: ActivatedRoute,
private documentaryService: DocumentaryService,
private router: Router,
private cd: ChangeDetectorRef) {}
editorConfig: AngularEditorConfig = {
editable: true,
spellcheck: true,
height: '25rem',
minHeight: '5rem',
placeholder: 'Enter text here...',
translate: 'no',
uploadUrl: 'v1/images', // if needed
};
ngOnInit() {
this.route.data.subscribe(data => {
this.documentary = data;
console.log(this.documentary);
this.initForm();
})
}
initForm() {
let title = this.documentary.title;
let slug = this.documentary.slug;
let storyline = this.documentary.storyline;
let summary = this.documentary.summary;
let year = this.documentary.year;
let length = this.documentary.length;
let status = this.documentary.status;
let short_url = this.documentary.short_url;
let poster = this.documentary.poster;
this.editDocumentaryForm = new FormGroup({
'title': new FormControl(title, [Validators.required]),
'slug': new FormControl(slug, [Validators.required]),
'storyline': new FormControl(storyline, [Validators.required]),
'summary': new FormControl(summary, [Validators.required]),
'year': new FormControl(year, [Validators.required]),
'length': new FormControl(length, [Validators.required]),
'status': new FormControl(status, [Validators.required]),
'short_url': new FormControl(short_url, [Validators.required]),
'poster': new FormControl(poster, [Validators.required])
});
this.editDocumentaryForm.statusChanges.subscribe(
(status) => console.log(status)
);
}
onFileChange(event) {
let reader = new FileReader();
if(event.target.files && event.target.files.length) {
const [file] = event.target.files;
reader.readAsDataURL(file);
reader.onload = () => {
this.editDocumentaryForm.patchValue({
poster: reader.result
});
// need to run CD since file load runs outside of zone
this.cd.markForCheck();
};
}
}
onSubmit() {
console.log(this.editDocumentaryForm);
}
}
In routing make sure to name resolver with the same name 'data':
{ path: 'somepath', component: AdminDocumentaryEditComponent, resolve: { data: DocumentaryResolverService} }

How to get JSON data into Dialog Component

Before this, the JSON Data appears when hovering over the info icon. Now i wish to pass the JSON Data into a dialog when click the info icon. But i dont know how.
HTML
<h2 mat-dialog-title>Info</h2>
<mat-dialog-actions>
<button mat-button (click)="matDialogRef.close()">Ok</button>
</mat-dialog-actions>
Dialog-Component.ts
import { Component, OnInit, Input, Inject, ViewEncapsulation, HostListener } from '#angular/core';
import { MAT_DIALOG_DATA, MatDialogRef} from '#angular/material';
import { FormBuilder, FormGroup, FormControl, Validators } from '#angular/forms';
import { PlannerProject } from 'app/services/planner-projects/planner-project';
#Component({
selector: 'app-my-dialog',
templateUrl: './my-dialog.component.html',
styleUrls: ['./my-dialog.component.scss']
})
export class MyDialogComponent implements OnInit {
#Input() project: PlannerProject;
projectData: string;
constructor(public matDialogRef: MatDialogRef<MyDialogComponent>,
#Inject(MAT_DIALOG_DATA) public data: any) { }
ngOnInit() {
}
ngOnChanges(event): void {
if (event.project !== undefined) {
this.projectData = JSON.stringify(this.project, null, 2);
}
}
ok(): void {
this.matDialogRef.close();
}
}
Delivery-Order.Component.ts
import { DeliveryOrderEditComponent } from './../delivery-order-edit/delivery-order-edit.component';
import { SelectionModel } from '#angular/cdk/collections';
import { Component, OnInit, ViewChild, OnDestroy, ElementRef, Input, OnChanges } from '#angular/core';
import { ActivatedRoute, Router } from '#angular/router';
import { PlannerProjectsService } from 'app/services/planner-projects/planner-projects.service';
import { map, switchMap, tap, debounceTime, distinctUntilChanged } from 'rxjs/operators';
import { DeliveryOrdersService } from '../delivery-orders.service';
import { Observable, of, Subscription, fromEvent } from 'rxjs';
import * as moment from 'moment';
import { MatPaginator, MatSort, PageEvent, MatTableDataSource, MatDialog } from '#angular/material';
import * as _ from 'lodash';
import { FuseSidebarService } from '#fuse/components/sidebar/sidebar.service';
import { DeliveryOrder } from '../delivery-order';
import { MyDialogComponent } from './../my-dialog/my-dialog.component';
import { PlannerProject } from 'app/services/planner-projects/planner-project';
import { FuseConfirmDialogComponent } from '#fuse/components/confirm-dialog/confirm-dialog.component';
import { UploadExcelService } from 'app/services/upload-excel.service';
#Component({
selector: 'app-delivery-orders',
templateUrl: './delivery-orders.component.html',
styleUrls: ['./delivery-orders.component.scss']
})
export class DeliveryOrdersComponent implements OnInit, OnDestroy, OnChanges {
#Input() project: PlannerProject;
#ViewChild(MatPaginator) paginator: MatPaginator;
#ViewChild(MatSort) sort: MatSort;
selection: SelectionModel<DeliveryOrder>;
importId: string;
dataTable;
sub: Subscription;
projectData : string;
// _filter: string;
_sortBy: string;
_sortOrder = 'asc';
_pageSize = 10;
_pageIndex = 1;
_options = {
pageSize: 100,
pageSizeOptions: [100, 150, 200, 250]
};
_displayedColumns = [
{ displayName: 'Location Name', column: 'locationName', sort: true },
{ displayName: 'Delivery Address', column: 'address', sort: false },
{ displayName: 'Is Valid', column: 'isValid', sort: false },
{ displayName: 'Import At', column: 'importedAt', sort: false },
{ displayName: 'File Name', column: 'importFileName', sort: false },
// { displayName: '', column: '' },
// { displayName: '', column: '' },
];
_displayColumns: string[] = ['selectRow', 'locationName', 'address', 'quantity', 'weight', 'volume', 'remarks', 'importedAt', 'actions'];
_actions = [
{
text: 'Edit',
action: (row) => {
console.log(`row`, row);
}
}
];
_dataSource: MatTableDataSource<DeliveryOrder>; // = new DeliveryOrdersDataSource(this.deliveryOrderService, '');
_filter: string | Observable<string>;
// #ViewChild('listHeader') listHeader: PageListTemplateComponent;
#ViewChild('search') search: ElementRef;
constructor(private route: ActivatedRoute,
private router: Router,
private projectService: PlannerProjectsService,
private deliveryOrderService: DeliveryOrdersService,
private uploadExcelService: UploadExcelService,
private _matDialog: MatDialog) { }
openDialog(): void {
const Ref = this._matDialog.open(MyDialogComponent, {
});
Ref.afterClosed().subscribe(result => {
console.log('The dialog was closed');
console.log(result);
});
}
ngOnInit(): void {
this.initDataTable();
}
ngOnDestroy(): void {
console.log(`destroy`);
if (this.sub) {
this.sub.unsubscribe();
}
}
ngOnChanges(): void {
if (this.project !== undefined) {
this.projectData = JSON.stringify(this.project, null, 2);
this.loadList(this.project.importId).toPromise().then((data) => {
console.log(`data`, data);
_.map(data, this.formatData.bind(this));
this.dataTable = data;
this._dataSource.data = this.dataTable;
this.selection = new SelectionModel<DeliveryOrder>(true, []);
});
}
So when i click the info icon, it shall display the JSON data in the dialog box. i also added the Delivery-order.component. I dont know much about JSON, so im very weak in trying to solve this problem to make the JSON values show up
When you create your dialog in delivery-component you can define input data for your dialog component, in this way:
const Ref = this._matDialog.open(MyDialogComponent, {
data: { id: 'id-value' }
});
Then you can recover your data in your dialog component:
constructor(public matDialogRef: MatDialogRef<MyDialogComponent>,
#Inject(MAT_DIALOG_DATA) public data: any) {
console.log(this.data.id);
}
In this example this.data will contain the data passed from your main component to dialog, the id field is only an example, you can pass whatever you want to dialog component.
Try something like this.
First method will open dialog and will pass all the data of the project
openDialog(): void {
const Ref = this._matDialog.open(MyDialogComponent, { data: this.project });
And in the dialog just use as the #Simo said
This will Inject the passed data from component to dialog
constructor(public matDialogRef: MatDialogRef<MyDialogComponent>,
#Inject(MAT_DIALOG_DATA) public data: any) {
console.log(this.data);
}

Can't print nested JSON data with Angular 6

I'm learning to code and just ran into this issue with Angular 6 which I can't seem to solve. I was able to get JSON's data before but now that it's nested I don't know how to get it's data. This is what I've done so far
Service
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class TestService {
url = "http://localhost:80/assets/data/test.json";
constructor(private http:Http) { }
getTestWithObservable(): Observable<any> {
return this.http.get(this.url)
.map(this.extractData)
.catch(this.handleErrorObservable);
}
private extractData(res: Response) {
let body = res.json();
return body;
}
private handleErrorObservable (error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.message || error);
}
}
Component
import { Component, OnInit } from '#angular/core';
import { Observable } from 'rxjs';
import { TestService } from './test.service';
#Component({
selector: 'ngx-test',
styleUrls: ['./test.component.scss'],
templateUrl: './test.component.html',
})
export class TestComponent implements OnInit {
observableTest: Observable<any>
errorMessage: String;
constructor(private testService: TestService) { }
ngOnInit(): void {
this.testService.getTestWithObservable().subscribe(
res => {
let user = res[0]["users"];
let user_data = user["data"];
console.log(user_data["name"]);
}
);
}
}
JSON
[{
"id": 1,
"users": {
"user_id": 14,
"data": [{
"name": "James",
"age": 20
},
{
"name": "Damien",
"age": 25
}]
}
}]
HTML
<div *ngFor="let x of user_data; let i = index">
{{x.name}}
</div>
I'd appreciate if someone can point me out the solution or what I'm doing wrong.
You need to save the data in an instance property to access it. user_data is local to your function, you cannot access it in the template so you should use something like this :
export class TestComponent implements OnInit {
observableTest: Observable<any>
errorMessage: String;
user_data: any;
constructor(private testService: TestService) { }
ngOnInit(): void {
this.testService.getTestWithObservable().subscribe(
res => {
let user = res[0]['users'];
let user_data = user['data'];
console.log(user_data['name']);
this.user_data = user_data; // here
}
);
}
}
There is some problems with your code:
export class TestComponent implements OnInit {
observableTest: Observable<any>
errorMessage: String;
user_data: any;
constructor(private testService: TestService) {
}
ngOnInit(): void {
this.testService.getTestWithObservable().subscribe(
res => {
let user = res[0]["users"];
this.user_data = user["data"];
console.log(user_data["name"]);
}
);
}
}
In Angular >= 4, pipe methods is better to handle Observable
this.http.get(this.url)
.pipe(
filter(...),
map(...)
)
With HttpClient (Http is deprecated), the .json() is done for you. You don't need your extractData function.
You have to initialize your variable. And use "this" to refer to it.

How to implement datasource for a datatable in Angular 5

I been trying to follow all the tutorials, and answers that I have found and I just can't make it work yet. Any help is appreciated it. I got this error:
Error: Provided data source did not match an array, Observable, or DataSource
And this is the JSON response I get from the server:
{receivedDate: "2018-05-22T00:00:00", id: "27280371", companyName: "Dark&Stormy", documentType: 11, receipts: Array(1), …}
And this is my code:
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, FormControl } from '#angular/forms';
import { HttpClient, HttpHeaders, HttpRequest, HttpEventType, HttpResponse } from '#angular/common/http';
import { Router, ActivatedRoute, ParamMap } from '#angular/router';
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';
import { DataSource } from '#angular/cdk/collections';
import { MatPaginator, MatSort, MatTableDataSource } from '#angular/material';
import { myService } from './../../../api';
import { InputService } from './../input.service';
import { IReceipt } from './../models/receipt.model';
#Component({
selector: 'app-submission-details',
templateUrl: './submission-details.component.html',
styleUrls: ['./submission-details.component.css']
})
export class SubmissionDetailsComponent implements OnInit {
setPaymentMethodForm: FormGroup;
submissionList = [];
errorMessage: string;
private documentId;
receipt: IReceipt;
dataSource = new MatTableDataSource();
displayedColumnsReceipt = ['id', 'fromDate', 'pReference', 'pMethod', 'status', 'valid', 'receipt'];
constructor(
private client: myService.Client,
private fb: FormBuilder,
private inputService: InputService,
private router: Router,
private activatedRoute: ActivatedRoute
) {
this.createForm();
activatedRoute.data
.subscribe(
data => this.documentId = data[this.documentId]
);
}
id: string;
private document: any;
ngOnInit() {
this.activatedRoute.params.subscribe(params => {
if (params['id']) {
this.id = params['id'];
console.log('paramsId: ', this.id);
this.inputService.getDocumentId(this.id)
.subscribe(res => {
this.dataSource = res;
console.log('sub-details.res: ', res);
});
}
});
}
getSubmissionDetails(string): void {
this.client.apiSubmissionGetSubmissionDocumentGet('documentId')
.subscribe(
data => {
this.submissionList = this.submissionList;
console.log('data: ', data);
},
(error: any) => this.errorMessage = <any> error);
}
createForm() {
this.setMethodForm = this.fb.group({
documentId: '',
receiptType: ''
});
}
}
Here
this.dataSource = res;
Whats res? Is it array? If so then
this.dataSource.data = res;

Angular ignoring JSON fields on Object instantiation

I am trying to query the wagtail API that will return JSON in a very unfriendly format.
{
"id": 3,
"meta": {
"type": "home.HomePage",
"detail_url": "http://localhost:8000/api/v1/pages/3/"
},
"parent": null,
"title": "Homepage",
"body": "<h2>cool an h2 fgf</h2>",
"main_image": {
"id": 1,
"meta": {
"type": "wagtailimages.Image",
"detail_url": "http://localhost:8000/api/v1/images/1/"
}
},
"header_image": {
"id": 1,
"meta": {
"type": "wagtailimages.Image",
"detail_url": "http://localhost:8000/api/v1/images/1/"
}
},
"show_in_menus": true,
"full_url": "/media/images/Background-4.original.jpg"
}
All I really want from that is a class like this.
export class HomePage {
id: number;
title: string;
body: string;
full_url: string;
}
But whenever I get back from the data back from my service and try and log it, it is undefined.
Is there any way for me to ignore the fields I don't want from a JSON in typescript?
The service I am using is:
import { Injectable } from '#angular/core';
import {Http, Response} from '#angular/http';
import {Observable} from "rxjs";
import {HomePage} from "./HomePage";
#Injectable()
export class HomePageService {
constructor(private http: Http){
}
getHomePage(GUID: number): Observable<HomePage>{
return this.http
.get("http://localhost:8000/api/v1/pages/" + GUID + "/")
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || {}
}
private handleError (error: Response | any) {
// In a real world app, we might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
And the component:
import {Component, OnInit, OnDestroy} from '#angular/core';
import {HomePageService} from './home-page.service';
import {ActivatedRoute} from '#angular/router';
import {HomePage} from "./HomePage";
#Component({
selector: 'app-home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.css'],
providers: [HomePageService]
})
export class HomePageComponent implements OnInit, OnDestroy{
id: number;
private sub: any;
public homePage: HomePage;
errorMessage: string;
constructor(private homePageService : HomePageService, private route: ActivatedRoute) {
}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.id = +params['id'];
});
this.homePageService.getHomePage(this.id)
.subscribe(
homePage => this.homePage = new HomePage(homePage),
error => this.errorMessage = <any>error,
() => console.log(this.homePage.full_url)
);
console.log(this.id);
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
homePage => this.homePage = new HomePage(homePage) - in your code I don't see a constructor defined for HomePage class. So when you pass the homePage object to it, nothing happens. Try this:
export class HomePage{
id: number;
title: string;
body: string;
full_url: string;
constructor(homePageObj: any)
{
if (homePageObj)
{
this.id = homePageObj.id;
this.title = homePageObj.title;
this.body = homePageObj.body;
this.full_url = homePageObj.full_url;
}
}
}