Angular 2 RC4 Unable to use Formbuilder - angularjs

Everytime when I try to use the formbuilder it crashes.
Can't resolve all parameters for the FormtestComponent
When I remove the
constructor(private _fb: FormBuilder) { }
I don't get this error.
Do you have any idea what the problem could be?
import { Component, OnInit } from '#angular/core';
import { REACTIVE_FORM_DIRECTIVES, FormGroup,
FormBuilder, Validators } from '#angular/forms';
#Component({
selector: 'formtest',
templateUrl: './app/formtest/formtest.component.html',
styleUrls: ['./app/formtest/formtest.component.css'],
directives: [REACTIVE_FORM_DIRECTIVES]
})
export class FormtestComponent {
myForm: FormGroup;
constructor(private _fb: FormBuilder) { }
}
Bootstrapper.ts
import { Main } from "./main";
import { bootstrap } from "#angular/platform-browser-dynamic";
import { disableDeprecatedForms, provideForms } from "#angular/forms";
bootstrap(Main, [
disableDeprecatedForms(),
provideForms()
]);

Related

Passing an array between pages in ionic 2

I'm new in Ionic 2 and I'm having troubles with passing data between pages. In my Home.ts file I have a global array that contains some numbers I calculated and i want to pass it to my Table.ts file, to show it in a HTML table with the *ngFor method.
this is the Function in Home.ts where i fill the array and try to push (i will skip the calculations, becacause i know they are correct).
`import { Component } from '#angular/core';
import { AlertController } from 'ionic-angular';
import { IonicPage,NavController, NavParams} from 'ionic-angular';
import {Table} from '../table/table';
export class HomePage {
averagesList: Array <number> =[];
constructor(public alerCtrl: AlertController,
public navCtrl: NavController,
public navParams: NavParams)
{}
Calculate(){
var Averages=[];
//Calculations on the 'Averages' Array
this.averagesList = Averages;
this.navCtrl.push(Table,this.averagesList);
}
}
So I try to print it in my Table.ts file but it gives me undefined result
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {HomePage} from '../home/home';
#IonicPage()
#Component({
selector: 'page-table',
templateUrl: 'table.html',
})
export class Table{
constructor(public navCtrl: NavController, public navParams: NavParams) {
}
ionViewDidLoad() {
console.log(this.navParams.get('averagesList'));
}
}
I've tried to pass a let variable and it worked, so why doesn't it work with arrays?
Your mistake is using console.log(this.navParams.get('averagesList'));
Here 'averagesList' is the key.
To get it this way, you need to send as :
this.navCtrl.push(Table,{'averagesList' : this.averagesList});
Else:
if you directly send as
this.navCtrl.push(Table,this.averagesList);
You can retrieve value like so:
console.log(this.navParams.data);
you can use services to do so. Just like in angular2 you can import your service within the constructor and use the property like this.
import {OnInit} from '#angular/core';
import {someService} from ./somepath;
...
export class someClass implements OnInit{
let myTmpVar; //we will capture the shared data in this variable
constructor (private smService: someService){ ... }
ngOnInit{
this.myTmpVar = this.smService.SharedServiceData;
}
...
}
It's better to use service for passing nested data. In your case calculations object.
You can create messageService and listen to changes, something like below.
import {Injectable} from '#angular/core';
import {Observable} from 'rxjs';
import {Subject} from 'rxjs/Subject';
#Injectable()
export class LocalMsgService {
private subject = new Subject();
sendMessage(message) {
this.subject.next(message);
}
clearMessage() {
this.subject.next();
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
Which can be used in your home.ts and table.ts pages as follows
Home.ts
//other imports comes here
import {LocalMsgService} from 'services/localMsg';
#Component({
selector: 'home-component',
templateUrl: 'home.html'
})
export class HomePage {
constructor( private msgService: LocalMsgService) {
}
dataToPass() {
console.log(this.averagesList);
this.msgService.sendMessage(this.averagesList);
}
}
Table.ts
//other imports comes here
import {LocalMsgService} from 'services/localMsg';
import {Subscription} from 'rxjs/Subscription';
#Component({
selector: 'page-table',
templateUrl: 'table.html',
})
export class TablePage{
items: any;
subscription: Subscription;
constructor(
public localMsgService : LocalMsgService) {
this.subscription = this.localMsgService.getMessage().subscribe(msg => {
this.items = msg;
});
}
}

Angular 2 EXCEPTION: TypeError: Cannot read property 'next' of undefined

I am trying to update a variable from my service to component. when i try to subscribe to it in the component i am getting error. can anyone help me please.
import {Injectable, } from 'angular2/core';
import {Router} from 'angular2/router';
import {MasterComponent} from '././master/master.component';
import 'rxjs/Rx';
import { Observable } from "rxjs/Observable";
import { Subscription } from "rxjs/Subscription"
import {Subject} from "rxjs/Subject"
#Injectable()
export class ConnectService
{
showValues: string;
public showValuesChange: Subject<string> = new Subject<string>();
constructor() {
this.showValues="1";
}
recvNotify(m) {
buttonName = innervalue;
console.log("ELSEinnervalue",buttonName);
switch (buttonName) {
case "0x01010000":
console.log('showValue==1');
this.showValues = "1";
this.showValuesChange.next(this.showValues);
break;
case "0x01020000":
console.log('showValue==2');
this.showValues = "2";
this.showValuesChange.next(this.showValues);
$('#showValue').prop("value",2);
break;
default:
console.log('showValue==3');
this.showValues = "3";
this.showValuesChange.next(this.showValues);
break;
}
}
}
Component: Here i want to get the updated showValues from the service when ever there is a change in the value.
import {Component} from 'angular2/core';
import {ConnectService} from '../connect.service';
import {Router} from 'angular2/router';
import 'rxjs/Rx';
import {Observable} from 'rxjs/Observable';
import {Subscription} from 'rxjs/Subscription';
#Component({
selector: 'Master',
templateUrl: './app/master/master.component.html',
providers: [ConnectService]
})
export class MasterComponent {
//showValue: any;
public showValues: string;
//show: any;
constructor(
public connectService: ConnectService,
public _router: Router,
public _subscription: Subscription){
if(localStorage.getItem("clientStatus")=='connected'){
this.showValues = connectService.showValues;
this._subscription = connectService.showValuesChange.subscribe((value) => {
this.showValues=value;
console.log("import {Observable} from 'rxjs/Observable';",this.showValues);
});
this._router.navigate(['Master']);
} else {
this._router.navigate(['Home']);
}
}
ngOnDestroy() {
this._subscription.unsubscribe();
}
}

Angular 2 Communicating with <router-outlet> components

I have a search bar in a header component.
Beneath that, I have a "router-outlet" in that same component.
The search bar (input txtfield), once enter is pressed, needs to send the search string (event.target.value) to the component that resides within the router-outlet beneath it so that it can run a method to return the results.
I have no clue what the best way is to achieve this.
UPDATED with code..
app.component.html:
<div class="white-container">
<input name="searchStr" [(ngModel)]="searchStr" (keyup.enter)="searchCourse($event)">
</div>
<router-outlet></router-outlet>
app.component.ts:
import { Component, OnInit } from '#angular/core';
import { CourseService } from './services/courses.service';
import { Course } from './Course';
#Component({
selector: 'my-app',
templateUrl: 'app.component.html',
providers: [CourseService]
})
export class AppComponent implements OnInit {
constructor(private _courseService: CourseService) {
}
searchCourse(event) {
// the user search string here...
}
}
/course-listings/course-listings.component.ts:
import { Component, OnInit } from '#angular/core';
import { CourseService } from './services/courses.service';
import { Course } from './Course';
#Component({
selector: 'app-course-listings',
templateUrl: './course-listings.component.html',
styleUrls: ['./course-listings.component.css'],
providers: [CourseService]
})
export class AppComponent implements OnInit {
course: Course[];
constructor(private _courseService: CourseService) {
}
searchCourse(evt) {
// This works once it's fired...
this._courseService.findCourse(evt)
.subscribe(courses => {
this.course = courses;
});
}
}
/services/courses.service.ts:
import {Injectable} from '#angular/core';
import {Http} from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class CourseService {
constructor(private _http:Http) {
}
getCourses(search) {
return this._http.get('/api/v1/courses/'+search)
.map(res => res.json());
}
}
FIX FOUND
Günter Zöchbauer was correct. I used a service w/ subscribe and observables to do it. Thanks.
An event.subscriber would be required in the constructor to pass to router-outlet.
Similar to the answer in this Angular 2 router event listener.
So, once the click is done, the subscriber event will be executed based on on the navigationend event, then the value can be accessed.

Ng2 <Component> is not a known element

I have browsed the other similar posts on stackoverflow, but have not found one that helps my cause, so here goes:
I am using angular2 based on the webpack "boiler-plate" from angular.io and included the routing bit.
I end up with this error even though the current setup is extremely minimal:
Unhandled Promise rejection: Template parse errors:
'Mathador' is not a known element:
1. If 'Mathador' is an Angular component, then verify that it is part of this module.
...
Here are the relevant code fragments
app/app.html
<main>
<h1>Mathador prototype</h1>
<router-outlet></router-outlet>
</main>
**app/app.routes.ts**
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomeComponent } from './pages/home/home'
const appRoutes: Routes = [
{
path: '', component: HomeComponent
}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
**app/app.ts**
import { Component } from '#angular/core';
import '../../public/css/styles.css';
#Component({
selector : 'my-app',
templateUrl : './app.html',
styleUrls : ['./app.scss']
})
export class AppComponent {
}
**app/app.module.ts**
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { routing } from './app.routes';
// core
import { AppComponent } from './app';
// pages
import { HomeComponent } from './pages/home/home';
// components
import { Mathador } from './components/mathador/mathador';
#NgModule({
imports: [
BrowserModule,
routing
],
declarations: [
AppComponent,
HomeComponent,
Mathador
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
**app/pages/home/home.ts**
import { Component } from '#angular/core';
#Component({
selector : 'my-home',
templateUrl : './home.html',
styleUrls : ['./home.scss']
})
export class HomeComponent {
constructor() {
// Do stuff
}
}
**app/pages/home/home.html**
<h1>home!</h1>
<Mathador></Mathador>
**app/components/mathador.html**
<div>transclusion succesfull!</div>
**app/components/mathador.ts**
// Importing core components
import {Component} from '#angular/core';
#Component({
selector : 'mathador',
templateUrl : './mathador.html'
})
export class Mathador {
constructor() { }
}

User Authentication before Appcomponent is loaded in Angular2

I have a simple application which loads material design Ui through Appcomponent. I need to Authenticate the user before the app component is loaded.
The app component is as follows
import {Component} from 'angular2/core';
import {Router, RouteConfig, ROUTER_DIRECTIVES,CanActivate} from 'angular2/router';
import {AuthHttp,AuthConfig, tokenNotExpired, AUTH_PROVIDERS} from 'angular2-jwt';
import {HomeComponent} from '../home/HomeComponent'
import {AboutComponent} from '../about/AboutComponent'
import {HeaderComponent} from './HeaderComponent'
import {LoginComponent} from '../login/LoginComponent'
import {AuthService} from '../../services/AuthService'
import {SidebarComponent} from './SidebarComponent'
import {DashboardComponent} from './DashboardComponent'
import {MDL} from './MaterialDesignLiteUpgradeElement';
#RouteConfig([
{path: 'app/home', component: HomeComponent, as: 'Home'},
{path: 'app/dashboard', component: DashboardComponent, as: 'Dashboard'},
{path: 'app/about', component: AboutComponent, as: 'About'},
{path: 'app/login', component: LoginComponent, as: 'Login'},
{path: 'app/*', redirectTo: ['Login']} // this redirect is not working for some reason
])
#Component({
selector: 'my-app',
/*template: '<router-outlet></router-outlet>',*/
template: `
<body>
<div class="demo-layout mdl-layout mdl-js-layout mdl-layout--fixed-drawer mdl-layout--fixed-header">
<app-header mdl class="demo-header mdl-layout__header mdl-color--grey-100 mdl-color-text--grey-600"></app- header>
<app-sidebar class="demo-drawer mdl-layout__drawer mdl-color--blue-grey-900 mdl-color-text--blue-grey-50">
</app-sidebar>
<main class="mdl-layout__content mdl-color--grey-100">
<router-outlet></router-outlet>
</main>
</div>
<script src="https://code.getmdl.io/1.1.3/material.min.js"></script>
</body>
`,
/*styleUrls: ['../app/assets/styles.css'], */
directives: [ROUTER_DIRECTIVES,SidebarComponent,HeaderComponent,MDL],
providers: [AUTH_PROVIDERS,AuthService]
})
export class AppComponent {
constructor() {}
}
I have a login component which logs in the user as follows
import {Component} from 'angular2/core';
import {Router, RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {AuthHttp,AuthConfig, tokenNotExpired, AUTH_PROVIDERS} from 'angular2-jwt';
import {AuthService} from '../../services/AuthService'
#Component({
selector: 'protected',
template: '',
directives: [ROUTER_DIRECTIVES],
providers: [AUTH_PROVIDERS,AuthService]
})
export class LoginComponent {
constructor(private auth: AuthService) {
this.auth.login();
}
login() {
this.auth.login();
}
logout() {
this.auth.logout();
}
static loggedIn() {
return tokenNotExpired();
}
}
The login component uses the AuthService
AuthService
import {Injectable} from 'angular2/core';
import {ROUTER_DIRECTIVES, Router} from "angular2/router";
declare var Auth0Lock: any;
#Injectable()
export class AuthService {
constructor(private router: Router) {}
lock = new Auth0Lock('KEY','URL');
login() {
this.lock.show((error: string, profile: Object, id_token: string) => {
if (error) {
console.log(error);
return false;
}
localStorage.setItem('profile', JSON.stringify(profile));
localStorage.setItem('id_token', id_token);
this.router.navigate(['Home']);
});
}
logout() {
localStorage.removeItem('profile');
localStorage.removeItem('id_token');
}
}
I tried annotating the AppComponent with #CanActivate as follows
but that doesn't seems to be working as the AppComponent is loaded any how.
#CanActivate(() => LoginComponent.loggedIn())
export class AppComponent {
}
Any ideas how to prevent the appComponent from loading without authnetication ?
You could implement your own RouterOutlet which overrides the acitvate method to check, if the person is allowed to navigate to that route.
import {Directive, DynamicComponentLoader, ElementRef} from "angular2/core";
import {AuthService} from '../../services/AuthService'
import {Router, RouterOutlet, ComponentInstruction} from "angular2/router";
#Directive({
selector: 'auth-router-outlet'
})
export class AuthRouterOutlet extends RouterOutlet {
private _protectedRoutes = {
'app/home': true,
'app/dashboard': true,
'app/about': true
};
constructor(_elementRef: ElementRef, _loader: DynamicComponentLoader, private _router: Router, nameAttr: string, private _authService: AuthService) {
super(_elementRef, _loader, _router, nameAttr);
}
activate(nextInstruction: ComponentInstruction): Promise<any> {
if (this._protectedRoutes[nextInstruction.urlPath]) {
if (!this._authService.loggedIn()) {
this._router.navigate(['Login']);
}
}
return super.activate(nextInstruction);
}
}
In your AppComponent just replace the <router-outlet></router-outlet> with <auth-router-outlet></auth-router-outlet>.
For the redirect in your RouteConfig use two asterisks like this:
#RouteConfig([
{path: 'app/home', component: HomeComponent, as: 'Home'},
{path: 'app/dashboard', component: DashboardComponent, as: 'Dashboard'},
{path: 'app/about', component: AboutComponent, as: 'About'},
{path: 'app/login', component: LoginComponent, as: 'Login'},
{path: 'app/**', redirectTo: ['Login']} // two asterisks here
])

Resources