I am using Angular 8
where I am facing error - -> ERROR in customer component **Cannot find module 'async_hooks'.**
ERROR in src/app/customer/customer.component.ts:7:27 - error TS2307: Cannot find module 'async_hooks'.
7 import { currentId } from 'async_hooks';
I tried to search on google about this error, But suggestions show the error is more related to Node
Well I tried to import { currentId } from 'async_hooks'; in my module but still showing same error
Just wanted to inform the I am using Angular material table
https://material.angular.io/components/table/overview
I am sharing my customer.component.ts have a look on it
import { Component, OnInit, ViewChild } from '#angular/core';
import { CustomerService } from '../_service/customer/customer.service';
import {MatTableDataSource} from '#angular/material/table';
import {MatPaginator} from '#angular/material/paginator';
import { MatSort } from '#angular/material';
import { trigger, state, transition, style, animate } from '#angular/animations';
import { currentId } from 'async_hooks';
#Component({
selector: 'app-customer',
templateUrl: './customer.component.html',
styleUrls: ['./customer.component.scss'],
animations: [
trigger('detailExpand', [
state('collapsed', style({height: '0px', minHeight: '0'})),
state('expanded', style({height: '*'})),
transition('expanded <=> collapsed', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)')),
]),
],
})
export class CustomerComponent implements OnInit {
columnsToDisplay: string[] = ['customerName', 'customerPhone', 'customerEmail', 'created_at'];
dataSource : any;
expandedElement : any;
addCustomer : boolean = false;
ProposalByCustomer : any;
constructor(public rest : CustomerService) { }
ngOnInit(){
this.getCustomer();
}
getCustomer() {
this.rest.getCustomers(localStorage.getItem('currentUser')).subscribe(result => {
console.log(result);
if(result['status'] == 1){
this.dataSource = result['value'];
}
});
}
applyFilter(filterValue: string) {
this.dataSource.filter = filterValue.trim().toLowerCase();
if (this.dataSource.paginator) {
this.dataSource.paginator.firstPage();
}
}
getProposalByCustomer(customer){
console.log(customer);
let token = localStorage.getItem('currentUser');
console.log(token);
let data = {customerId : customer.customerId};
console.log(data);
this.rest.getProposalByCustomer(data , token).subscribe(result => {
console.log(result);
if(result['status'] == 1){
this.ProposalByCustomer = result['data'];
}
})
}
addCustmr() {
this.addCustomer = !this.addCustomer;
}
}
Related
I want to add my website a user's profile updater. But when I try to open user's profile in my website, I have that error in Angular:
main.ts:6 ERROR SyntaxError: Unexpected token 'e', "eyJhbGciOi"... is not valid JSON
at JSON.parse (<anonymous>)
at LocalStorageService.getItem (local-storage.service.ts:17:22)
at get getDecodedToken [as getDecodedToken] (auth.service.ts:39:42)
at get getCurrentUserId [as getCurrentUserId] (auth.service.ts:44:29)
at UserComponent.getUserById (user.component.ts:51:51)
at UserComponent.ngOnInit (user.component.ts:28:10)
at callHook (core.mjs:2752:22)
at callHooks (core.mjs:2721:17)
at executeInitAndCheckHooks (core.mjs:2672:9)
at refreshView (core.mjs:12084:21)`
My local-storage.service.ts:
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root'
})
export class LocalStorageService {
constructor() { }
setItem(key:string, value:any){
let json = JSON.stringify(value);
localStorage.setItem(key, json);
}
getItem(key:string){
let json = localStorage.getItem(key);
let value = JSON.parse(json);
return value;
}
isSaved(key: string) {
if (localStorage.getItem(key)) {
return true;
}
return false;
}
remove(key: string) {
localStorage.removeItem(key);
}
removeAll() {
localStorage.clear();
}
}
auth.service.ts:
`import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { LoginModel } from '../models/loginModel';
import { SingleResponseModel } from '../models/singleResponseModel';
import { TokenModel } from '../models/tokenModel';
import { LocalStorageService } from './local-storage.service';
import { UserPasswordModel } from '../models/userPasswordModel';
import { ResponseModel } from '../models/responseModel';
import { JwtHelperService } from '#auth0/angular-jwt';
#Injectable({
providedIn: 'root'
})
export class AuthService {
apiUrl="https://localhost:5001/api/auth/";
public jwtHelperService: JwtHelperService = new JwtHelperService();
constructor(private httpClient:HttpClient,
private localStorageService:LocalStorageService) {}
login(user:LoginModel){
return this.httpClient.post<SingleResponseModel<TokenModel>>(this.apiUrl+"login", user);
}
isAuthenticated(){
if (localStorage.getItem("token")) {
return true;
}else{
return false;
}
}
updatePassword(userPasswordModel:UserPasswordModel){
let newUrl = this.apiUrl + "updatepassword";
return this.httpClient.post<ResponseModel>(newUrl, userPasswordModel)
}
get getDecodedToken() {
let token = this.localStorageService.getItem("token");
return this.jwtHelperService.decodeToken(token);
}
get getCurrentUserId() {
let decodedToken = this.getDecodedToken;
let userIdString = Object.keys(decodedToken).filter((t) =>
t.endsWith('/nameidentifier')
)[0];
let userId: number = decodedToken[userIdString];
return userId;
}
}
user.component.ts:
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { ToastrService } from 'ngx-toastr';
import { User } from 'src/app/models/user';
import { AuthService } from 'src/app/services/auth.service';
import { ProfileService } from 'src/app/services/profile.service';
#Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
user:User;
profileForm:FormGroup;
passwordForm:FormGroup;
dataLoaded = false;
constructor(
private userService:ProfileService,
private authService:AuthService,
private formBuilder:FormBuilder,
private toastrService:ToastrService
) { }
ngOnInit(): void {
this.getUserById();
this.createProfileForm();
this.createPasswordForm();
}
createProfileForm(){
this.profileForm = this.formBuilder.group({
id:[Number(this.authService.getCurrentUserId)],
firstName: ["",Validators.required],
lastName:["",Validators.required]
})
}
createPasswordForm(){
this.passwordForm = this.formBuilder.group({
userId:[Number(this.authService.getCurrentUserId)],
oldPassword: ["",Validators.required],
newPassword:["",Validators.required],
repeatNewPassword:["",Validators.required]
})
}
getUserById(){
this.userService.getUserById(this.authService.getCurrentUserId)
.subscribe(response=>{
this.user = response.data
this.dataLoaded = true
});
}
updateUserNames(){
if (this.profileForm.valid) {
let userModel = Object.assign({}, this.profileForm.value);
this.userService.updateUserNames(userModel).subscribe(response=>{
this.toastrService.info(response.message, "Bilgiler Güncellendi.");
setTimeout(() => {
window.location.reload();
}, 1000);
}, responseError=>{
console.log(responseError);
this.toastrService.error(responseError.error, "Hata!");
});
} else {
this.toastrService.error("Lütfen tüm alanları doldurunuz.", "Hata!");
}
}
updatePassword(){
if (this.passwordForm.valid) {
let passwordModel = Object.assign({}, this.passwordForm.value);
console.log(passwordModel);
this.authService.updatePassword(passwordModel).subscribe(response=>{
this.toastrService.info(response.message, "Şifre Güncellendi");
}, responseError=>{
this.toastrService.error(responseError.error, "Hata!");
});
} else {
this.toastrService.error("Lütfen tüm alanları doldurunuz.", "Hata!");
}
}
}
How can I fix this error? Thanks. I tried lots of thins, but no-one helped me.
I am trying to add a user's profile updater. But this error...
As the error says; Unexpected token 'e', "eyJhbGciOi"... is not valid JSON. You are trying to parse a plain string represents token itself, not a valid string represents a json object.. Therefore it fails when trying to parse it.
Either update the code where you directly store your token as string on your local storage or just use localStorage.getItem('token') without parsing.
EDIT: I made changes in the push method but it still did not work
I am making get request to an api and pushing each of the responses to an array. The array is visible when logged to console. On printing the length of the array in the template length comes out to be 5. But when I try to iterate through it using ngFor no output is being displayed
Service
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import {Quote} from 'src/app/models/quote';
#Injectable({
providedIn: 'root'
})
export class StockpriceService {
url1='https://financialmodelingprep.com/api/v3/quote-short/';
url2='?apikey=efa24b272821b542c459557332c02a1e';
constructor(private http:HttpClient) {
}
//alpha apikey="VETRGM94G70WQGX9";
getQuote(symbol:string) //load data from api
{
return this.http.get<Quote>(this.url1 + symbol + this.url2);
}
}
ts file
import { Component, OnInit } from '#angular/core';
import{Quote} from 'src/app/models/quote';
import{StockpriceService} from 'src/app/services/stockprice.service';
import { timer } from 'rxjs';
#Component({
selector: 'app-stocks',
templateUrl: './stocks.component.html',
styleUrls: ['./stocks.component.css']
})
export class StocksComponent implements OnInit {
stocks: Array<Quote>=[];
symbols=['AAPL', 'GOOG', 'FB', 'AMZN', 'TWTR'];
constructor(private serv:StockpriceService) { }
ngOnInit(): void {
this.symbols.forEach(symbol => {
this.serv.getQuote(symbol).subscribe(
(data:Quote)=>{
console.log(data);
this.stocks.push(
{
symbol:data.symbol,
price:data.price,
volume:data.volume
}
);
}
)
});
console.log('stocks array is')
console.log(this.stocks);
}
}
Template
<div *ngFor="let stock of stocks">
{{stock.symbol}}
{{stock.price}}
</div>
sample api response
[ {
"symbol" : "AAPL",
"price" : 126.81380000,
"volume" : 36245456
} ]
Accordingly I have an interface defined for it as
export interface Quote{
symbol:string;
price:number;
volume:number;
}
This will work fine.
this.serv.getQuote(symbol).subscribe((data: Quote[]) => {
console.log(data);
this.stocks.push(...data);
});
Dear I am developing a page with Angular 7 and I am presented with the error TS2559: Type 'BookInterface[]' has no properties in common with type 'BookInterface', I have changed the code but I still can not find the solution, I leave the code below, the error is thrown in the method getListBooks(): this is my file list-books.component.ts
import { BookInterface } from './../../../models/book';
import { DataApiService } from './../../../services/data-api.service';
import { Component, OnInit } from '#angular/core';
import {NgForm} from '#angular/forms';
#Component({
selector: 'app-list-book',
templateUrl: './list-book.component.html',
styleUrls: ['./list-book.component.css']
})
export class ListBookComponent implements OnInit {
constructor(private dataApi: DataApiService) { }
private books: BookInterface = {};
ngOnInit() {
this.getListBooks();
}
getListBooks() {
this.dataApi.getAllBooks().subscribe(books => {
this.books = books;
});
}
onDelete() {
console.log('LIBRO ELIMINADO');
}
}
I also leave the code of my data-api.service.ts from where I call the interface
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs/internal/Observable';
import { Injectable } from '#angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from '#angular/fire/firestore';
import { BookInterface } from '../models/book';
#Injectable({
providedIn: 'root'
})
export class DataApiService {
constructor(private afs: AngularFirestore) {
this.bookCollecction = afs.collection<BookInterface>('books');
this.books = this.bookCollecction.valueChanges();
}
private bookCollecction: AngularFirestoreCollection<BookInterface>;
private books: Observable<BookInterface[]>;
private bookDoc: AngularFirestoreDocument<BookInterface>;
private book: Observable<BookInterface>;
getAllBooks() {
return this.books = this.bookCollecction.snapshotChanges()
.pipe(map( changes => {
return changes.map( action => {
const data = action.payload.doc.data() as BookInterface;
data.id = action.payload.doc.id;
return data;
});
}));
}
// metodo que trae un libro a traves de su id
getOneBook(idBook: string) {
this.bookDoc = this.afs.doc<BookInterface>(`books/${idBook}`);
return this.book = this.bookDoc.snapshotChanges().pipe(map(action => {
if (action.payload.exists === false){
return null;
} else {
const data = action.payload.data() as BookInterface;
data.id = action.payload.id;
return data;
}
}));
}
addBook(book: BookInterface): void {
this.bookCollecction.add(book);
}
updateBook(book: BookInterface): void {
let idBook = book.id;
this.bookDoc = this.afs.doc<BookInterface>(`books/${idBook}`);
this.bookDoc.update(book);
}
deleteBook(idBook: string): void {
this.bookDoc = this.afs.doc<BookInterface>(`books/${idBook}`);
this.bookDoc.delete();
}
}
The version of typescript that I am currently using is Version 2.7.2, but also update it without solving the problem
You need to change the following:
private books: BookInterface = {};
to:
private books: BookInterface[] = [];
My code was working previously, displaying the data from an API correctly after using the reduce function.
I pulled my files from github on a new machine and suddenly I'm getting this error. Any help is greatly appreciated, as I've tried what I can to figure out what I've done wrong.
"ERROR TypeError: tickets.reduce is not a function
at SectionDashboardComponent.push../src/app/Sections/section-
dashboard/section-
dashboard.component.ts.SectionDashboardComponent.getTicketData (section-dashboard.component.ts:30)"
Here's the ts page where this error seems to be occurring:
import { Component, OnInit } from '#angular/core';
import { freshServiceService } from
'src/app/Services/freshservice.service';
import { Ticket } from 'src/app/Domain/Ticket';
#Component({
selector: 'app-section-dashboard',
templateUrl: './section-dashboard.component.html',
styleUrls: ['./section-dashboard.component.css']
})
export class SectionDashboardComponent implements OnInit {
constructor(private _freshServiceService: freshServiceService) { }
private ticketCounts: number[];
private ticketResponders: string[];
ngOnInit() {
this._freshServiceService.fetchTickets().subscribe
(
data =>
{
console.log(data);
this.getTicketData(data);
}
);
}
private getTicketData(tickets: Ticket[]): void {
const mappedTickets = tickets.reduce((x, y) => {
{x[y.responder_name] = x[y.responder_name] + 1 || 1};
return x;
}, []);
this.ticketResponders = Object.keys(mappedTickets);
this.ticketCounts = Object.values(mappedTickets);
console.log(this.ticketResponders);
console.log(this.ticketCounts);
}
}
I am having issues using a promise to return a Degree object in Angular 2. The first return statement (uncommented) in degree.service works just fine in combination with the uncommented implementation of getDegree() in build.component. However, when I try to switch to either of the commented implementations using a promise, the object always comes back as "undefined"
degree.service.ts
import { Injectable } from '#angular/core';
import { Degree } from '../components/degree';
import { Category } from '../components/category';
import { Course } from '../components/course';
import { SAMPLE } from '../components/mock-degree';
#Injectable()
export class DegreeService{
getDegree(){
return SAMPLE;
// return Promise.resolve(SAMPLE);
// return new Promise<Degree>(function (resolve, reject) {
// resolve(SAMPLE);
// })
}
}
build.component.ts
import { Component, Input, OnInit } from '#angular/core';
import { SEMANTIC_COMPONENTS, SEMANTIC_DIRECTIVES } from "ng-semantic";
import { Course } from '../course';
import { Category } from '../category';
import { PaneComponent } from './pane/pane.component';
import { Degree } from '../degree';
import { DegreeService } from '../../services/degree.service';
const blank: Category = {
name: '',
rank: 1,
rulestat: 'no',
categories: [],
courses: []
}
#Component({
selector: 'my-build',
directives: [SEMANTIC_COMPONENTS, SEMANTIC_DIRECTIVES, PaneComponent],
templateUrl: `app/components/build/build.component.html`,
providers: [DegreeService]
})
export class BuildComponent implements OnInit{
constructor(private degreeService: DegreeService){}
level: number = 1;
currDeg: Degree;
parents = [blank, blank, blank, blank];
setLast(lst: Category){ //pass category objects, do all UI changing here
this.level = lst.rank + 1;
this.parents[lst.rank - 1] = lst;
}
getDegree(){
//this.degreeService.getDegree().then(deg => this.currDeg = deg)
this.currDeg = this.degreeService.getDegree();
}
ngOnInit(){
this.getDegree();
}
}
I don't know how you use the currDeg in your template but with promises, things are asynchronous. So the corresponding object will be undefined at the beginning since it will be set later (when the promise is resolved). And this, even if the promise is directly resolved with Promise.resolve.
export class DegreeService{
getDegree(){
return Promise.resolve(SAMPLE);
}
}
#Component({
selector: 'my-app',
providers: [DegreeService],
templateUrl: 'src/app.html'
})
export class App {
constructor(private degreeService:DegreeService) {
}
getDegree(){
this.degreeService.getDegree().then(deg => {
this.currDeg = deg;
console.log('this.currDeg = ' + this.currDeg); // <------
});
}
ngOnInit(){
this.getDegree();
}
}
See this plunkr: https://plnkr.co/edit/1fxE0okyMNj2JktURY4w?p=preview.