I am trying to create Login/SignUp in ionic angular 3.3.0.
I get the error Cannot find module '../providers/auth-service/auth-service'. in the login.ts file. Please Help!
auth-service.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
/*
Generated class for the AuthServiceProvider provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
export class User {
name: string;
email: string;
constructor(name: string, email: string) {
this.name = name;
this.email = email;
}
}
#Injectable()
export class AuthServiceProvider {
currentUser: User;
public login(credentials) {
if (credentials.email === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
return Observable.create(observer => {
// At this point make a request to your backend to make a real check!
let access = (credentials.password === "pass" && credentials.email === "email");
this.currentUser = new User('ian', 'ianlikono#gmail.com');
observer.next(access);
observer.complete();
});
}
}
public register(credentials) {
if (credentials.email === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
// At this point store the credentials to your backend!
return Observable.create(observer => {
observer.next(true);
observer.complete();
});
}
}
public getUserInfo() : User {
return this.currentUser;
}
public logout() {
return Observable.create(observer => {
this.currentUser = null;
observer.next(true);
observer.complete();
});
}
}
login.ts
import { Component } from '#angular/core';
import { NavController, AlertController, LoadingController, Loading, IonicPage } from 'ionic-angular';
import { AuthServiceProvider } from '../providers/auth-service/auth-service';
#IonicPage()
#Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
loading: Loading;
registerCredentials = { email: '', password: '' };
constructor(private nav: NavController, private auth: AuthServiceProvider, private alertCtrl: AlertController, private loadingCtrl: LoadingController) { }
public createAccount() {
this.nav.push('RegisterPage');
}
public login() {
this.showLoading()
this.auth.login(this.registerCredentials).subscribe(allowed => {
if (allowed) {
this.nav.setRoot('HomePage');
} else {
this.showError("Access Denied");
}
},
error => {
this.showError(error);
});
}
showLoading() {
this.loading = this.loadingCtrl.create({
content: 'Please wait...',
dismissOnPageChange: true
});
this.loading.present();
}
showError(text) {
this.loading.dismiss();
let alert = this.alertCtrl.create({
title: 'Fail',
subTitle: text,
buttons: ['OK']
});
alert.present(prompt);
}
}
ScreenShot Program structure:
From your project structure, your login.ts is inside login folder, and login folder is inside pages folder.
So in order to reach providers folder, you need to write
'../../providers/auth-service/auth-service'
This should move you out of two folders which should solve the issue.
If you are using VS Code, install the plugin called "Typescript Hero" and "Typescript Toolbox", will help you with your imports.
Actually "Typescript Toolbox" shows a lightbulb when you focus your cursor on an imported element and you can select from the lightbulb the import. Very usefull.
Related
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?
Full error message:
"Type 'Observable' is not assignable to type 'DataListeItem[]'.
Property 'includes' is missing in type 'Observable'."
I'm using material Table Schematic and now I want to fill the list from my Rest service.
data-liste-datasource.ts
import { DataSource } from '#angular/cdk/collections';
import { MatPaginator, MatSort } from '#angular/material';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';
import { AuthService } from '../auth.service';
export interface DataListeItem {
name: string;
id: number;
email: string;
number: number;
}
export class DataListeDataSource extends DataSource<DataListeItem> {
data: DataListeItem[] = this.authservice.GetUser(); <-- error here!
constructor(private paginator: MatPaginator, private sort: MatSort, private authservice: AuthService) {
super();
}
connect(): Observable<DataListeItem[]> {
const dataMutations = [
observableOf(this.data),
this.paginator.page,
this.sort.sortChange
];
this.paginator.length = this.data.length;
return merge(...dataMutations).pipe(map(() => {
return this.getPagedData(this.getSortedData([...this.data]));
}));
}
disconnect() { }
private getPagedData(data: DataListeItem[]) {
const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
return data.splice(startIndex, this.paginator.pageSize);
}
private getSortedData(data: DataListeItem[]) {
if (!this.sort.active || this.sort.direction === '') {
return data;
}
return data.sort((a, b) => {
const isAsc = this.sort.direction === 'asc';
switch (this.sort.active) {
case 'name': return compare(a.name, b.name, isAsc);
case 'email': return compare(a.email, b.email, isAsc);
case 'id': return compare(+a.id, +b.id, isAsc);
case 'number': return compare(+a.number, +b.number, isAsc);
default: return 0;
}
});
}
}
function compare(a, b, isAsc) {
return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
auth.service.ts
import { Injectable } from '#angular/core';
import { HttpHeaders, HttpClient } from '../../node_modules/#angular/common/http';
import { Observable } from '../../node_modules/rxjs';
import { DataListeItem } from './data-liste/data-liste-datasource';
#Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) { }
GetUser(): Observable<DataListeItem[]> {
return this.http.get<DataListeItem[]>("DataListeItem.online");
}
So all in all how to I make a call to my REST and get the list shown.
Should I make the call directly in " data-liste-datasource.ts" or should that be in the service.
thanks for reading
You need to use Observable<DataListeItem[]> instead of DataListeItem[].
data: Observable<DataListeItem[]> = this.authservice.GetUser();
when I try to test the app in Ionic serve command, I didn't get any error. But when i try to publish the app, I get the error as "property json does not exist on type object" . The error takes place during the transpile stage:
How to solve this problem? I tried with every possibility, but i didn't get my problem solved.
Home.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { WeatherProvider } from '../../providers/weather/weather';
import { Storage } from '#ionic/storage';
//import { Response } from '#angular/http';
//import 'rxjs/add/operator/map';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
weather:any;
location:{
city:string,
state:string
}
constructor(
public navCtrl: NavController,
private weatherProvider:WeatherProvider,
private storage: Storage) {
}
ionViewWillEnter(){
this.storage.get('location').then((val)=>{
if(val!=null){
this.location = JSON.parse(val);
}else{
this.location = {
city: 'Chennai',
state: 'TN'
}
}
this.weatherProvider.getWeather(this.location.city,this.location.state)
// .map((res: Response) => res.json() )
.subscribe(weather => {
this.weather = weather.current_observation;
});
});
}
}
Weather.ts
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
//import { Response } from '#angular/http';
//import 'rxjs/add/operator/map';
//import 'rxjs/Rx';
#Injectable()
export class WeatherProvider {
apiKey = '6d3243fb22b01d0c';
url;
constructor(public http: HttpClient) {
console.log('Hello WeatherProvider Provider');
this.url = 'http://api.wunderground.com/api/'+this.apiKey+'/conditions/q';
}
getWeather(city, state){
return this.http.get(this.url+'/'+state+'/'+city+'.json')
// .map(res => res.json());
// .map((res: Response) => res.json() );
}
}
Typescript is all about typing. So you should state the type of object you'are receiving from the method getWeather. Start by creating a class Weather at the end of home.ts (look below)
class Weather {
current_observation: string;
}
and make this change:
this.weatherProvider.getWeather(this.location.city,this.location.state)
// .map((res: Response) => res.json() )
.subscribe((weather: Weather) => {
this.weather = weather.current_observation;
});
});
}
ionViewWillEnter(){
this.storage.get('location').then((val) => {
if(val != null){
this.location = JSON.parse(val);
} else{
this.location ={
city: 'miami',
state: 'FL'
}
}
//Try below code
this.weatherprovider.getweather(this.location.city, this.location.state).subscribe(result => {
let weather:any = result;
this.weather = weather.current_observation;
console.log(this.weather);
});
});
}
I've seen a few answers to this question and tried all of them, but it still isn't working. I'm kinda trying to write a CMS in angular 2; so a backend where someone puts HTML and a frontend that renders said HTML. I am able to display some HTML with DomSanitizer.bypassSecurityTrustHtml() but not others. For example, I am able to add an <img class="center" src=""> but a <button md-button>test</button> is rendered as a plain HTML button. I also have a LessonComponent w/a lesson selector, but it isn't rendered at all on the page, I do see the <lesson></lesson> HTML in the inspector.
How (if possible) do I display components on the page from a DB? Code below:
lesson.ts
import { Component, Inject, Input, SecurityContext } from '#angular/core';
import { MdDialog, MD_DIALOG_DATA } from '#angular/material';
import { Lesson, LessonService } from '../lesson.service';
import { DomSanitizer, SafeHtml} from '#angular/platform-browser';
#Component({
selector: 'lesson',
templateUrl: './lesson.html',
styleUrls: ['./lesson.scss']
})
export class LessonComponent {
#Input() lessonID: number = 0;
#Input() questionID: string = '';
lesson: Lesson;
constructor(public service: LessonService, public dialog: MdDialog, private sanitizer: DomSanitizer) { }
getLesson(): object {
if(!this.service.getLesson(this.lessonID)) { return {}; }
let lesson = this.service.getLesson(this.lessonID)['pages'].filter(lesson => {
return lesson['id'] === this.questionID;
})[0];
if(lesson && lesson['buttons']) {
this.service.buttons = lesson['buttons'];
} else {
this.service.buttons = [];
}
lesson['test'] = this.sanitizer.bypassSecurityTrustHtml(lesson['content']);
return lesson;
}
doClick(btnID) {
let button = this.getLesson()['buttons'].filter(btn => {
return btn['id'] === btnID;
})[0];
this.dialog.open(ExtraDialog, { data: button['content'] });
}
}
#Component({
selector: 'extra-dialog',
template: `{{data}}`
})
export class ExtraDialog {
constructor(#Inject(MD_DIALOG_DATA) public data: any) {}
}
lesson.html
<div *ngIf="!getLesson()" >
Error: Lesson {{lessonID}} -> question {{questionID}} is not a known lesson or question. Please click <a routerLink="/lesson/1">here</a> to go to the first lesson.
</div>
<div *ngIf="getLesson() && getLesson()['buttons']">
<span *ngFor="let button of getLesson()['buttons']">
<button md-mini-fab (click)="doClick(button.id)"><md-icon>{{button.icon}}</md-icon></button>
</span>
</div>
<div *ngIf="getLesson()">
<h2>{{getLesson()['title']}}</h2>
<p [innerHTML]="getLesson()['test']"></p>
</div>
lesson.service.ts
import { Injectable } from '#angular/core';
import { AngularFireDatabase, FirebaseObjectObservable } from 'angularfire2/database';
export class Lesson {
constructor(public id: number, public pages: Object[]) { }
}
#Injectable()
export class LessonService {
private lessons: Lesson[] = [];
public buttons: object[];
constructor(public db: AngularFireDatabase) {
this.db.object('/lessons', { preserveSnapshot: true }).subscribe(lessons => {
this.lessons = [];
lessons.forEach(lesson => {
let pages = [];
if(lesson.val()['pages']) {
Object.keys(lesson.val()['pages']).forEach(key => {
let page = {
id: key,
title: lesson.val()['pages'][key]['title'],
content: lesson.val()['pages'][key]['content']
};
let buttons = lesson.val()['pages'][key]['buttons'];
if(buttons) {
page['buttons'] = [];
Object.keys(buttons).forEach(key => {
page['buttons'].push({
content: buttons[key]['content'],
icon: buttons[key]['icon'],
id: key
});
});
}
pages.push(page);
});
}
this.lessons.push(new Lesson(
lesson.key,
pages
));
});
});
}
getLessons() { return this.lessons; }
getLesson(id: number): Lesson {
return this.lessons.filter(lesson => {
return lesson['id'] == id;
})[0];
}
}
I have one screen, which have two gridview . each grid view will populate some value after api calling. so my page will have 2 api calling. so when i call my api call method under constructor or ionViewDidEnter its not working. it allowing only one method to exeute.
here is my two api call method on one page .ts
Even i put under my constructor. But its not showing the data. so if i want to call the both api and need to display the data means how can i do that.please help me out. i was not able to find it out !!
Thanks in advance
updated:
import { Component, ViewChild } from '#angular/core';
import { AlertController, App, FabContainer, ItemSliding, List, ModalController, NavController, ToastController, LoadingController, Refresher } from 'ionic-angular';
import { CategoryDetailPage } from '../categorydetail/categorydetail';
import { ConferenceData } from '../../providers/conference-data';
import { UserData } from '../../providers/user-data';
import { SessionDetailPage } from '../session-detail/session-detail';
import { ScheduleFilterPage } from '../schedule-filter/schedule-filter';
import {Http, Headers } from '#angular/http';
import 'rxjs/add/operator/map';
import { AuthService } from '../../providers/AuthService';
#Component({
selector: 'page-speaker-list',
templateUrl: 'speaker-list.html'
})
export class SpeakerListPage {
loading: any;
data: any;
Catdata: any;
Catdatanames: any;
resdata: any;
resCatdata: any;
resCatdatanames: any;
loginData: {username?: string} = {};
resloginData: {username?: string} = {};
constructor(
public alertCtrl: AlertController,
public app: App,
public loadingCtrl: LoadingController,
public modalCtrl: ModalController,
public navCtrl: NavController,
public toastCtrl: ToastController,
public confData: ConferenceData,
public user: UserData,
public http:Http,
public authService: AuthService
) {
}
ionViewDidEnter() {
this.show();
this.another();
}
show() {
this.showLoader();
this.authService.subs(this.loginData).then((result) => {
this.loading.dismiss();
this.data = result;
if(this.data.status == 1)
{
this.Catdata = this.data.SubjectList;
//this.Catdata.forEach(category => console.log(category.CatID));
for(let i=0; i<this.Catdata.length; i++) {
// console.log(this.Catdata[i].SubjectName);
}
}
else if(this.data.status == 0) {
let alert = this.alertCtrl.create({
title: 'Error',
subTitle: 'Please Enter Valid Username & Password',
buttons: ['OK']
});
alert.present();
}
}, (err) => {
this.loading.dismiss();
});
}
another() {
this.authService.allresources(this.resloginData).then((result) => {
this.resdata = result;
if(this.resdata.status == 1)
{
this.resCatdata = this.resdata.SubjectList;
for(let i=0; i<this.resCatdata.length; i++) {
// console.log(this.resCatdata[i].FileName);
}
}
else if(this.resdata.status == 0) {
let alert = this.alertCtrl.create({
title: 'Error',
subTitle: 'Please Enter Valid Username & Password',
buttons: ['OK']
});
alert.present();
}
}, (err) => {
});
}
showLoader(){
this.loading = this.loadingCtrl.create({
content: 'Authenticating...'
});
this.loading.present();
}
}