I am new to Angular. I am using version 8. In the process of learning Angular 8, I am trying to develop a CRUD Application and I am success to integrate with Angular's "InMemoryDbService". Here is the code.
This is data.service.ts
import { Injectable } from '#angular/core';
import {InMemoryDbService} from 'angular-in-memory-web-api';
#Injectable({
providedIn: 'root'
})
export class DataService implements InMemoryDbService {
constructor() { }
createDb() {
let persons = [
{ id: 1, firstName: 'A', lastName: 'B', emailId: 'AB#mail.com' },
{ id: 1, firstName: 'C', lastName: 'D', emailId: 'CD#gmail.com' },
{ id: 1, firstName: 'E', lastName: 'F', emailId: 'EF#gmail.com' },
{ id: 1, firstName: 'G', lastName: 'H', emailId: 'GH#mail.com' },
];
return {persons};
}
}
Here is my person.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
import {Person} from './person';
#Injectable({
providedIn: 'root'
})
export class PersonService {
private baseUrl = 'http://localhost:8082/api/persons';
constructor(private http: HttpClient) { }
getPerson(id: number): Observable<any> {
return this.http.get(`${this.baseUrl}/${id}`);
}
createPerson(person: Person) {
return this.http.post(`${this.baseUrl}`, person);
}
updatePerson(id: number, value: any): Observable<object> {
return this.http.put(`${this.baseUrl}/${id}`, value);
}
deletePerson(id: number): Observable<any> {
return this.http.delete(`${this.baseUrl}/${id}`);
}
getPersonsList(): Observable<any> {
return this.http.get(`${this.baseUrl}`);
}
}
Now, I would like to do the same stuff by using google chrome's WebSQL database. I am not getting the right way to integrate that one. I saw lot of examples just using HTML5 along with Websql.(I will be able to do this by connecting to any REST API. But, I would like to do this completely from UI side).
But, I haven't seen such examples which are explaining the integration of Angular 8 with Websql.
How effectively I can make my Angular 8 service class to use WebSql?
Any one please help me.
Thanks.
Related
I'm working on simple book management app. When user clicks on "Add to favorites, That book will be added to favorites page. Up to now, I have build start page, login page, and register page. I'm using JSON as a database (books.json and users.json) and using JSON-server to host the data. Here my Question is, When the new user is created, How to create Empty Wishlist automatically? And based on Mail id, how to get Id of that object? I have tried some methods in YouTube and documentation. but I was failed.
user.json
[
{
"id": 1,
"userName":"Deepak Sharma",
"Password":"dep#123!",
"Phone":"9988776655",
"Email":"Deepak#gmail.com",
"UserType":"Customer",
"WishList": [1,2,3],
"Completed":[4,5,6]
},
{
"username": "test1",
"Password": "test1",
"Phone": 123456,
"Email": "test1#gmail.com",
"id": 2
}
]
login-page.component.ts
import { HttpClient } from '#angular/common/http';
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { Router } from '#angular/router';
#Component({
selector: 'app-login-page',
templateUrl: './login-page.component.html',
styleUrls: ['./login-page.component.css']
})
export class LoginPageComponent implements OnInit {
public loginForm!: FormGroup;
constructor(private formBuilder : FormBuilder, private http: HttpClient, private router: Router) { }
ngOnInit(): void {
this.loginForm = this.formBuilder.group({
Email: ['', Validators.required],
Password: ['', Validators.required]
})
}
login(){
this.http.get<any>("http://localhost:3500/Users")
.subscribe(res=>{
const user = res.find((a:any) =>{
return a.email === this.loginForm.value.email && a.password === this.loginForm.value.password
});
if (user) {
alert("Login Success!");
this.loginForm.reset();
this.router.navigate(['user'])
} else {
alert("User Not found. Create account !!");
}
}, err=>{
alert("Something Went Wrong");
})
}
}
and here is the code favorite-page.component.ts
import { Component, OnInit, ViewChild } from '#angular/core';
import { LoginPageComponent } from '../login-page/login-page.component';
#Component({
selector: 'app-favourite-page',
templateUrl: './favourite-page.component.html',
styleUrls: ['./favourite-page.component.css']
})
export class FavouritePageComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
You can create a wish list with a format of your liking inside the function where you create the new user. The format can be JSON, a temporary array or an insert into a database.
I can also see that you're using a deprecated calling method of subscribe. Consider checking out the tutorials & documentation of Angular, rxjs an ngrx.
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?
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.
I'm trying to load an array of objects from a JSON and display them in my template with *ngFor in my angular2 app. I'm getting this error Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays..
I've found quite a bit of documentation on this particular error and a fix, but I'm having trouble understanding/translating it into a working fix. From what I understand the *ngFor will only render arrays of data and my home.component is trying to render an object of arrays.
The fix I've read is to write a pipe like this:
#Pipe({ name: 'values', pure: false })
export class ValuesPipe implements PipeTransform {
transform(value: any, args: any[] = null): any {
return Object.keys(value).map(key => value[key]);
}
}
I've tried this but then I'm getting an error that says compiler.umd.js?9df7:14126Uncaught Error: Unexpected value 'HomeComponent' declared by the module 'AppModule' I've built the pipe directly into my home component so I'm unsure why this is a problem.
Here is my code.
home.component.js
import { Component, OnInit, Pipe, PipeTransform } from '#angular/core';
import { Project } from './project';
import { ProjectService } from './project.service';
#Component({
selector: 'home',
templateUrl: './home.html',
styleUrls: ['./home.scss'],
providers: [ProjectService]
})
#Pipe({ name: 'values', pure: false })
export class ValuesPipe implements PipeTransform {
transform(value: any, args: any[] = null): any {
return Object.keys(value).map(key => value[key]);
}
}
export class HomeComponent implements OnInit {
errorMessage: string;
projects: Project[];
selectedProject: Project;
mode = 'Observable';
constructor(private projectService: ProjectService) { }
ngOnInit() { this.getProjects(); }
getProjects() {
this.projectService.getProjects()
.subscribe(
projects => this.projects = projects,
error => this.errorMessage = <any>error);
}
onSelect(project: Project): void {
this.selectedProject = project;
}
}
projects.service.js
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Project } from './project';
import { Observable } from 'rxjs/Observable';
#Injectable()
export class ProjectService {
private projectsUrl = 'data/project.json'; // URL to web API
constructor(private http: Http) { }
getProjects(): Observable<Project[]> {
return this.http.get(this.projectsUrl)
.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);
}
}
project.json
{
"project": [{
"title": "The Upper Crust",
"id": "upper-crust",
"year": "2016",
"category": ["Design", "Web Design"],
"thumbnail": "thumbnails/upper-crust.jpg"
}, (...)
}
Sorry if the answer is already out there I've spent a few hours last night and this morning trying to solve this issue and can't seem to figure it out. I appreciate your help in advance, I'm new to development and am at a loss with much of this stuff.
I've cloned tour of heroes tutorial product from angular team where demo data is storing in in-memory-data-service.ts. Since my preferred backend is django-rest-framework, I need to link them together.
For example, my heroes are translating from localhost:8000/api/v1/heroes/.
[
{
"name": "Greg",
"id": 5,
},
{
"name": "Krek",
"id": 6,
}
]
What should I do except removing in-memory-data-service.ts to replace heroes list with provided by django backend via json? It would be great if you'll tell me do I need model declaration
export class Hero {
id: number;
name: string;
}
yet if rest-framework gives me full objects structure stored in JSON.
To consume any REST API you have to write a service like below,
import { Injectable } from 'angular2/core';
import { Http, Response } from 'angular2/http';
import { Observable } from 'rxjs/Rx';
export class Hero {
id: number;
name: string;
}
#Injectable()
export class HeroService {
constructor(private _http: Http) { }
getHeroes() {
return this._http.get('api/v1/heroes')
.map((response: Response) => <Hero []>response.json())
}
}
Hope this helps!!