I am fatch data by username from django API using angular4 - django

this is my anglar4 creating app name as search i want to fatch data from django rest API. I want that when i give username it give me only this username data.
app.components.tc
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 {
username:string = '';
constructor(private httpClient:HttpClient){}
onNameKeyUP(event:any){
this.username = event.target.value;
}
getProfile(){
console.log(this.username)
this.httpClient.get("http://127.0.0.1:8000/loginAdmin/?username=${this.username}")
.subscribe(
(data:any[]) => {
console.log(data);
}
)
}
}
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { HttpClientModule } from '#angular/common/http';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.components.html
it is my simlple Html which is use to send username from Django API
<input type="text" (keyup)="onNameKeyUP($event)">
<button (click)="getProfile()">Get Profile</button>

Try this:
app.component.ts
import { Component, OnInit } from '#angular/core';
import { FormControl } from '#angular/forms';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import {
filter,
map,
switchMap,
debounceTime,
distinctUntilChanged,
} from 'rxjs/operators';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
profile$: Observable<any>;
ctrl = new FormControl();
constructor(private httpClient: HttpClient) {}
ngOnInit() {
this.profile$ = this.ctrl.valueChanges.pipe(
filter(v => v.length > 2),
debounceTime(400),
distinctUntilChanged(),
switchMap(username =>
this.httpClient.get(
`http://127.0.0.1:8000/loginAdmin/?username=${username}`,
),
),
);
}
}
app.component.html
<input [formControl]="ctrl">
<div> {{ profile$ | async | json }} </div>
app.module.ts
import { ReactiveFormsModule } from '#angular/forms';
#NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
ReactiveFormsModule,
...
],
providers: [...],
bootstrap: [AppComponent],
})
export class AppModule {
constructor() {}
}

Related

error NG8001: 'mat-form-field' is not a known element

Currently I am struggling with an error after try to use a few mat components like "mat-form-field" or "mat-date-range-input" etc..
I've already imported them in the app.module file as I always do with these kind of component, but I get many errors like this:
If 'mat-form-field' is an Angular component, then verify that it is part of this module
If 'mat-label' is an Angular component, then verify that it is part of this module.
I have to say that in the same project I am using mat-tab-group and mat-tab etc... and I have not any errors with them.
These is my code:
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AngularMaterialModule } from './angular-material.module/angular-material.module.module';
import { MatButtonToggleModule } from '#angular/material/button-toggle';
import { MatSlideToggleModule } from '#angular/material/slide-toggle';
import { MatCardModule } from '#angular/material/card';
import { MatFormFieldModule } from '#angular/material/form-field';
import { MatInputModule } from '#angular/material/';
import { MatIconModule } from '#angular/material/icon';
import { ClipboardModule } from '#angular/cdk/clipboard';
#NgModule({
declarations: [], // I've omitted this part because is not relevant to this issue
imports: [
BrowserModule,
AppRoutingModule,
AngularMaterialModule,
MatProgressSpinnerModule,
MatButtonToggleModule,
MatSlideToggleModule,
MatCardModule,
MatFormFieldModule,
MatInputModule,
MatIconModule,
ClipboardModule
],
providers: [{provide: LocationStrategy, useClass: PathLocationStrategy}],
bootstrap: [AppComponent]
})
export class AppModule { }
And my component : create.report.component.html
<mat-form-field appearance="fill">
<mat-label>Enter a date range</mat-label>
<mat-date-range-input [formGroup]="reportForm" [rangePicker]="picker">
<input matStartDate formControlName="from" placeholder="Start date">
<input matEndDate formControlName="to" placeholder="End date">
</mat-date-range-input>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>
create.report.component.ts
import { Component, OnInit } from '#angular/core';
import { FormBuilder, Validators, FormGroup, FormArray, FormControl } from '#angular/forms';
import { Router } from '#angular/router';
#Component({
selector: 'app-report',
templateUrl: './create.report.component.html'
})
export class CreateReportComponent implements OnInit {
reportForm = new FormGroup({
from: new FormControl(),
to: new FormControl()
});
constructor(
private router: Router,
private fb: FormBuilder) {
this.buildForm();
}
ngOnInit(): void {
}
buildForm() {
// console.log('***buildForm this.hmService***', this.hmService);
this.reportForm = this.fb.group( {
from : [ '', [Validators.required, Validators.minLength(5)]],
to: [ '', [Validators.required, Validators.minLength(5)]],
published : [ '', [Validators.required, Validators.minLength(5)]]
});
}
}
Ok, finally I solved!
With this line I fix the issue I had with material components. Now I can use them in my create.report.component .
import { CreateReportComponent } from './pages/report/create/create.report.component';

ionic 2: *ngFor not displaying data

ngFor Not working in the HTML.I am using only one module in my application.
I tried many solution but didn't solve this problem.
There isn't any error in console.
Here is my code
movie.ts
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
import { Storage } from '#ionic/storage';
#Component({
selector: 'page-movie',
templateUrl: 'movie.html',
})
export class Movie {
http: any;
movies_cats: any;
constructor(public navCtrl: NavController, public navParams: NavParams, private storage: Storage, http: Http) {
this.http = http;
return this.http.get('link.php?a=' + this.navParams.data.code + '&m=' + this.navParams.data.mac + '&s=' + this.navParams.data.serial + '&k=' + this.navParams.data.key + '&p=vodMovieList')
.map(res => res.json())
.subscribe(response => {
this.movies_cats = response.vod_categories.vod_category;
console.log(this.movies_cats);
});
}
}
movie.html
<ion-header>
<ion-navbar>
<ion-title>movie</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-grid class="grid_div">
<ion-row class="grid_row">
<ion-col col-3 class="grid_col">
<ion-scroll scrollY class="scroll_bar">
<div class="scroll-item" *ngFor="let cat of movies_cats">
<p>name</p>
</div>
</ion-scroll>
</ion-col>
<ion-col col-9>SUB CATEGORIES</ion-col>
</ion-row>
</ion-grid>
</ion-content>
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import {IonicStorageModule} from '#ionic/storage';
import { HttpModule} from '#angular/http';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { Categories } from '../pages/categories/categories';
import { Live } from '../pages/live/live';
import { Movie } from '../pages/movie/movie';
#NgModule({
declarations: [
MyApp,
HomePage,
Categories,Movie,Live
],
imports: [
BrowserModule,HttpModule,
IonicModule.forRoot(MyApp),IonicStorageModule.forRoot(),
IonicStorageModule.forRoot({
name: '__mydb',
driverOrder: ['indexeddb', 'sqlite', 'websql']
})
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
Categories,Movie,Live
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},Storage
]
})
export class AppModule {}
In the end I expect the div to be repeated 3 times such as the number of the objects in the response without printing cat.
The problem is that nothing appears in the HTML
import { FormsModule} from '#angular/forms';
import { CommonModule } from '#angular/common';
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
CommonModule
],

Module has no exported module named PeopleService - Ionic

I have been folllowing the ionic tutorial:
10 Minutes with Ionic 2: Calling an API
Typescript Error
Module '"C:/Users/grace/imaginemai/client/apiApp/src/providers/people->service/people-service"' has no exported member 'PeopleSevice'.
C:/Users/grace/imaginemai/client/apiApp/src/pages/home/home.ts
import { NavController } from 'ionic-angular';
import {PeopleSevice} from >'C:\Users\grace\imaginemai\client\apiApp\src\providers\people-> >service\people-service';
I am not sure what I am doing wrong. I noticed that there were possible errors with the original tutorial so I made some amendments as per a correction posted in the comments: https://github.com/ah3243/ionic2ApiExample/blob/master/src/providers/people-search.ts
I am still having issues - I've followed the tutorial but used my own API from a blog I am developing with Django. So although the ionic app is called peopleservice, I am expecting it to produce blog posts. The code is pasted below. Please could someone tell me what I am doing wrong.
Thanks in advance.
people-service.ts:
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the PeopleServiceProvider provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
#Injectable()
export class PeopleService {
data1: any;
constructor(public http: Http) {
console.log('Hello PeopleService Provider');
}
load() {
if (this.data1) {
return Promise.resolve(this.data1);
}
//dont have the data yet
return new Promise(resolve => {
this.http.get('localhost:8000/posts/')
.map(res => res.json())
.subscribe(data => {
this.data1 = data.results;
resolve(this.data1);
});
});
}
}
home.ts:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import {PeopleSevice} from 'C:\\Users\\grace\\imaginemai\\client\\apiApp\\src\\providers\\people-service\\people-service';
#Component({
selector: 'page-home',
templateUrl: 'home.html',
providers: [PeopleSevice]
})
export class HomePage {
public posts: any;
constructor(public navCtrl: NavController, public peopleService: PeopleService) {
this.loadPosts();
}
loadPosts() {
this.PeopleService.load()
.then(data1 => {
this.posts = data1;
})
}
}
app.module.ts:
import { NgModule, ErrorHandler } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
/*import { PeopleService } from 'C:\\Users\\grace\\imaginemai\\client\\apiApp\\src\\providers\\people-service\\people-service';*/
#NgModule({
declarations: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage
],
providers: [
/*StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
PeopleService*/
]
})
export class AppModule {}
app.component.ts:
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { TabsPage } from '../pages/tabs/tabs';
import { PeopleService } from 'C:\\Users\\grace\\imaginemai\\client\\apiApp\\src\\providers\\people-service\\people-service';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any = TabsPage;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
});
}
}
home.html:
<ion-header>
<ion-navbar *navbar>
<ion-title>
Home
</ion-title>
</ion-navbar>
</ion-header>
<ion-content class="home">
<ion-list>
<ion-item *ngFor="let post of posts">
<h2>{{post.title}}</h2>
<p>{{post.text}}</p>
</ion-item>
</ion-list>
</ion-content>
folder structure:
blog
>client
>apiApp
>src
>app
>app.component.ts
>app.html
>app.module.ts
>app.scss
>main.ts
>pages
>providers
>people-service
>people-service.ts
You have to use relative paths for importing.
import {PeopleSevice} from 'C:\\Users\\grace\\imaginemai\\client\\apiApp\\src\\providers\\people-service\\people-service';
This kind of absolute path will not work.
Try:
import {PeopleSevice} from '../../providers/people-service/people-service';
This is the relative path from the current file.

Angular 2 unit test case is not working for services with external module configuration

If I create a module with services using #Inject method is not working with Angular 2 Testbed Unit test cases. It is throwing No Provider for AppService Error.
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { AppComponent } from './app.component';
import { AppService } from './app.service';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [
{provide:'AppService',useClass:AppService}
],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component, Inject } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
constructor(#Inject('AppService') private appService) {}
getName() {
this.title = this.appService.getName();
}
setName(name) {
this.appService.setName(name);
}
}
app.service.ts
import { Injectable } from '#angular/core';
#Injectable()
export class AppService {
private name = 'dummy';
public getName() {
return this.name;
}
public setName(name) {
console.log("ser", name);
this.name = name;
}
}
app.component.spec.ts
import { Injectable} from '#angular/core';
import { TestBed, async, inject } from '#angular/core/testing';
import { AppComponent } from './app.component';
import { FormsModule } from '#angular/forms';
import { AppService } from './app.service';
describe('AppComponent', () => {
let fixture, comp, appService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [
AppComponent
],
providers: [AppService]
}).compileComponents();
fixture = TestBed.createComponent(AppComponent);
comp = fixture.debugElement.componentInstance;
appService = fixture.debugElement.injector.get(AppService);
});
it('should create the app', async(() => {
expect(comp).toBeTruthy();
}));
});
try adding providers: [AppService] in #Component in app.component.ts as below
#Component({
providers: [AppService],
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})

How should I Unit test Angular2 components and modules that has imported other modules (and components)

I have spent a while getting the hang of modules in Angular2 and really like them but I am a little uncertain as to best approach for testing both my modules and the components within. (I also realise that my app.component can and probably should be broken out more but for now it is helpful while learning the testing framework to be a little more complex)
For example this is my app.module:
import { createStore, compose, applyMiddleware } from 'redux';
import ReduxThunk from 'redux-thunk';
import { AUTH_PROVIDERS } from 'angular2-jwt';
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { ComponentsModule } from './components';
import { MaterialModule} from './material';
import { RouterModule } from '#angular/router';
import { AppComponent } from './app.component';
import { ViewsModule } from './+views';
import { rootReducer } from './dataStore';
import { CurrentUserModel } from './models/current-user'
const appStore = createStore(rootReducer, applyMiddleware(ReduxThunk));
const APP_DECLARATIONS = [
AppComponent
];
const APP_PROVIDERS = [
{ provide: 'AppStore', useValue: appStore },
CurrentUserModel
];
#NgModule({
imports:[
FormsModule,
BrowserModule,
RouterModule,// here as well as in our Views Module because of router-outlet
ViewsModule,
MaterialModule, // here as well as in our Views & componet Module because used in App componet
ComponentsModule
],
declarations: APP_DECLARATIONS,
bootstrap:[AppComponent],
providers: APP_PROVIDERS,
})
export class AppModule {
}
and this is what my app.component looks like:
import { Component, ViewChild, AfterViewInit } from '#angular/core';
import { Router } from '#angular/router';
#Component({
selector: 'app',
styleUrls:['app.component.scss'],
template: `
<md-toolbar>
<!-- <i class="material-icons demo-toolbar-icon">menu</i> -->
<span class="toolbar-brand">Franks</span>
<span *ngIf="searchActive" role="search" class="fill-remaining-space">
<span class="search-input-container flex flex-1">
<i class="material-icons search-link">search</i>
<input class="search-input" placeholder="Search" type="text" id="searchInput" #searchInput (keyup.esc)="exitSearch($event)"/>
</span>
</span>
<i *ngIf="searchActive" class="material-icons right selectable" (click)="exitSearch($event)">close</i>
<span *ngIf="!searchActive" class="fill-remaining-space">
</span>
<span *ngIf="!searchActive" role="navmenu">
<span class="hlink" routerLink="/" routerLinkActive="active">home</span>
<span class="hlink" routerLink="/profile" routerLinkActive="active">Profile</span>
<span class="hlink" routerLink="/login" routerLinkActive="active">Login</span>
<span class="hlink" routerLink="/signup" routerLinkActive="active">Sign Up</span>
<i class="material-icons search-link" (click)="activeSearch($event)">search</i>
</span>
</md-toolbar>
<div class="container">
<router-outlet></router-outlet>
</div>
`,
})
export class AppComponent {
#ViewChild('searchInput') searchInputRef;
ngAfterViewChecked() {
if(this.searchActive && this.searchInputRef){
console.log(this.searchInputRef);
this.searchInputRef.nativeElement.focus();
}
}
searchActive: boolean;
constructor(public router: Router) {
this.searchActive = false;
}
activeSearch(event):void {
this.searchActive = true;
}
exitSearch(event) : void {
this.searchActive = false;
}
}
So I know I can potentially mock out all the Components with for example the MaterialComponents (this is just a wrapper module for the material components) within my tests but this seems a little tedious. Is that my only options and if so does it make sense to make creating a mock of components when creating the components part of the process.
for informational purposes this is what my material module looks like and my views and components modules are similar:
import { NgModule } from '#angular/core';
// Material
import { MdCardModule } from '#angular2-material/card';
import { MdButtonModule } from '#angular2-material/button';
import { MdInputModule } from '#angular2-material/input';
import { MdToolbarModule } from '#angular2-material/toolbar';
import { MdListModule } from '#angular2-material/list';
import { MdIconModule, MdIconRegistry } from '#angular2-material/icon';
const MATERIAL_UI_MODULES = [
MdCardModule,
MdButtonModule,
MdInputModule,
MdToolbarModule,
MdIconModule,
MdListModule
]
const MATERIAL_UI_REGISTRIES = [
MdIconRegistry
]
#NgModule({
imports:[
...MATERIAL_UI_MODULES,
],
providers: MATERIAL_UI_REGISTRIES,
exports:[
...MATERIAL_UI_MODULES,
]
})
export class MaterialModule {
}
So I eventually figured out how to do this and this is my current solution:
/* tslint:disable:no-unused-variable */
import { TestBed, inject, async } from '#angular/core/testing';
import { RouterTestingModule } from '#angular/router/testing';
import { By } from '#angular/platform-browser';
import { Component,ViewChild, AfterViewChecked } from '#angular/core';
import { Router } from '#angular/router';
import { Location, CommonModule } from '#angular/common';
import { MaterialModule} from './material';
#Component({
template: '<div></div>'
})
class DummyComponent {
}
import { AppComponent } from './app.component';
describe('component: TestComponent', function () {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
CommonModule,
RouterTestingModule.withRoutes([
{ path: 'profile', component: DummyComponent },
{ path: 'login', component: DummyComponent },
{ path: 'signup', component: DummyComponent },
{ path: '', component: DummyComponent }
]),
MaterialModule
],
declarations: [ AppComponent, DummyComponent ]
});
});
it('should create the app', async(() => {
let fixture = TestBed.createComponent(AppComponent);
let app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it('should be navigate to correct url for each option in navmenu',
async(inject([Router, Location], (router: Router, location: Location) => {
let fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
fixture.debugElement.query(By.css('span.hlink[routerLink="/profile"]')).nativeElement.click();
fixture.whenStable().then(() => {
expect(location.path()).toEqual('/profile');
expect(fixture.debugElement.query(By.css('span.hlink[routerLink="/profile"]')).classes['active']).toBeTruthy();
expect(fixture.debugElement.nativeElement.querySelectorAll('span.hlink.active').length).toEqual(1)
fixture.debugElement.query(By.css('span.hlink[routerLink="/login"]')).nativeElement.click();
return fixture.whenStable();
}).then(() => {
expect(location.path()).toEqual('/login');
expect(fixture.debugElement.query(By.css('span.hlink[routerLink="/login"]')).classes['active']).toBeTruthy();
expect(fixture.debugElement.nativeElement.querySelectorAll('span.hlink.active').length).toEqual(1)
fixture.debugElement.query(By.css('span.hlink[routerLink="/signup"]')).nativeElement.click();
return fixture.whenStable();
}).then(() => {
expect(location.path()).toEqual('/signup');
expect(fixture.debugElement.query(By.css('span.hlink[routerLink="/signup"]')).classes['active']).toBeTruthy();
expect(fixture.debugElement.nativeElement.querySelectorAll('span.hlink.active').length).toEqual(1)
fixture.debugElement.query(By.css('span.hlink[routerLink="/"]')).nativeElement.click();
return fixture.whenStable();
}).then(() => {
expect(location.path()).toEqual('/');
expect(fixture.debugElement.query(By.css('span.hlink[routerLink="/"]')).classes['active']).toBeTruthy();
expect(fixture.debugElement.nativeElement.querySelectorAll('span.hlink.active').length).toEqual(1)
});
})));
});