While creating a modal in ionic 2 I am facing this error:
Error in ./QuizmePage class QuizmePage - caused by:
self.context.MyModal is not a function
can anyone please tell me how to overcome this error.
My code follows:
quiz.html page
<ion-content padding>
<button ion-button (click)="MyModal()">Share</button>
quiz.ts
import { Component } from '#angular/core';
import {ModalController, NavController, NavParams } from 'ionic-angular';
import { AccModal } from './modal'
#Component({
selector: 'page-quiz',
templateUrl: 'quiz.html'
})
export class QuizPage {
constructor(public navCtrl: NavController, public navParams: NavParams , public modalCtrl: ModalController ) {
}
MyModal() {
let myModal = this.modalCtrl.create(AccModal);
myModal.present();
}
}
modal.ts
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular/index';
#Component ({
template: `
<ion-card class='popover'>
<ion-card-content>
Hello
</ion-card-content>
</ion-card>
`
})
export class AccModal {
private dumbData: number;
constructor(private params: NavParams) {
this.dumbData= 22;
}
}
Related
Currently i'm developing a web app which shows the Golden State Warriors (Basketball Team) Roster.
My main goal consists in filtering all players by position.
Positions are numbers ordered from 1 to 5.
My question would be: which could be the way to transform my http get request in order to obtain the point-guards (position === 1) ??
roster-data.service.ts
import { Injectable } from '#angular/core';
import { Player } from "../models/player";
import { environment } from "../../environments/environment";
import {HttpClient, HttpErrorResponse} from '#angular/common/http';
import {Observable, throwError} from 'rxjs';
import {catchError, map, filter } from 'rxjs/operators';
#Injectable({
providedIn: 'root'
})
export class RosterDataService {
private readonly devURL = environment.url;
constructor(private http: HttpClient) {
}
jSON_Server_ReadPointGuards():Observable<Player[]> {
return this.http.get<Player[]>(`${this.devURL}/roster_GoldenStateWarriors`).pipe(
map(players => players.filter((player:Player) => player.position === 1)
),
catchError(this.handleError)
);
}
And then my interface
player.ts
export interface Player {
fullName: string,
shirtNumber: string,
position: number,
height: string,
weight: number,
points: number,
rebounds: number,
assists: number,
blocks: number,
steals: number,
imageFile: string,
imageDescrip: string
}
players.component.ts
import { Component, OnInit, isDevMode } from '#angular/core';
import { RosterDataService } from "../../services/roster-data.service";
import { Player } from "../../models/player";
import { imgRoute } from "../../services/img-route.service";
#Component({
selector: 'app-players',
templateUrl: './players.component.html',
styleUrls: ['./players.component.scss'],
providers: [RosterDataService]
})
export class PlayersComponent implements OnInit {
public imageLocation:string;
public bases!: Player[];
public escoltas!: Player[];
public aleros!: Player[];
public alaPivots!: Player[];
public pivots!: Player[];
public getPlayers: Player[] = [];
constructor(private _rosterDataService: RosterDataService) {
this.imageLocation = imgRoute.path;
}
ngOnInit(): void {
this.dev_SuscribeAllPointGuards();
// this.dev_SuscribeAllShootingGuards();
// this.dev_SuscribeAllSmallForwards();
// this.dev_SuscribeAllPowerForwards();
// this.dev_SuscribeAllCenters();
}
dev_SuscribeAllPointGuards(){
this._rosterDataService.jSON_Server_ReadPointGuards().subscribe(
pointguards => {
this.bases = pointguards;
}
);
}
}
players.component.html
<section>
<article>
<h4 id="pointGuard">{{ "players.firstTitle" | translate }}</h4>
<div class="gallery">
<div [routerLink]="'/'+(base.fullName | removespaces)+'/'+base.shirtNumber" *ngFor="let base of bases;">
<figure><img src="{{imageLocation + base.imageFile}}" alt="{{base.imageDescrip}}" title="{{base.imageDescrip}}"></figure>
<section>
<h5>{{base.fullName}}</h5>
<h6>{{base.shirtNumber}}</h6>
<h6>{{base.points}}</h6>
<h6>{{base.rebounds}}</h6>
<h6>{{base.assists}}</h6>
<h6>{{base.blocks}}</h6>
<h6>{{base.steals}}</h6>
</section>
</div>
</div>
</article>
</section>
I am trying to make this demo work but somehow it is not working for me. It keeps giving me error
servers.component.ts
import { Component } from '#angular/core';
import {FormControl} from '#angular/forms';
import {Observable} from 'rxjs/Observable';
import {startWith} from 'rxjs/operators/startWith';
import {map} from 'rxjs/operators/map';
#Component({
selector: 'app-servers',
templateUrl: './servers.component.html',
styleUrls: ['./servers.component.css']
})
export class User {
constructor(public name: string) { }
}
export class ServersComponent {
myControl = new FormControl();
options = [
new User('Mary'),
new User('Shelley'),
new User('Igor')
];
filteredOptions: Observable<User[]>;
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith<string | User>(''),
map(value => typeof value === 'string' ? value : value.name),
map(name => name ? this.filter(name) : this.options.slice())
);
}
filter(name: string): User[] {
return this.options.filter(option =>
option.name.toLowerCase().indexOf(name.toLowerCase()) === 0);
}
displayFn(user?: User): string | undefined {
return user ? user.name : undefined;
}
}
I have imported both User class and ServersComponent in app.module.ts.
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AlertModule } from 'ngx-bootstrap';
import "hammerjs";
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import {MatButtonModule, MatInputModule } from '#angular/material';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { ServerComponent } from './server/server.component';
import { ServersComponent, User } from './servers/servers.component';
import { MyFormComponent } from './my-form/my-form.component';
import {MatCheckboxModule} from '#angular/material/checkbox';
import {MatAutocompleteModule} from '#angular/material/autocomplete';
#NgModule({
declarations: [
AppComponent,
ServerComponent,
ServersComponent,
MyFormComponent,
User,
],
imports: [
BrowserModule,
BrowserAnimationsModule,
AlertModule.forRoot(),
FormsModule,
ReactiveFormsModule,
MatButtonModule,
MatInputModule,
MatCheckboxModule,
MatAutocompleteModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
However if i use this demo it is working fine.
Can you let me know what I am doing wrong in my code.
Problem lies in this line,
import { ServersComponent, User } from './servers/servers.component';
Usually you can have only one component from a select/component. Remove User from the same.
To add more on the issue, you should not export two classes from same component. change your component as,
import { Component } from '#angular/core';
import {FormControl} from '#angular/forms';
import {Observable} from 'rxjs/Observable';
import {startWith} from 'rxjs/operators/startWith';
import {map} from 'rxjs/operators/map';
#Component({
selector: 'app-servers',
templateUrl: './servers.component.html',
styleUrls: ['./servers.component.css']
})
export class ServersComponent {
myControl = new FormControl();
options = [
new User('Mary'),
new User('Shelley'),
new User('Igor')
];
filteredOptions: Observable<User[]>;
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith<string | User>(''),
map(value => typeof value === 'string' ? value : value.name),
map(name => name ? this.filter(name) : this.options.slice())
);
}
filter(name: string): User[] {
return this.options.filter(option =>
option.name.toLowerCase().indexOf(name.toLowerCase()) === 0);
}
displayFn(user?: User): string | undefined {
return user ? user.name : undefined;
}
}
I have an array with 4 items, and 4 buttons on a dashboard. I want to assign item1 with button1, and item2 with button2 etc. Right now it displays 4 buttons for each "hero" for a total of 16 buttons. I tried {{hero.name[2]}} and similar things but that just grabs letters and not the actual array items. I would appreciate any help.
dashboard.component.html
<h3>Calibrations</h3>
<div class="grid grid-pad">
<a *ngFor="let hero of heroes" [routerLink]="['/detail', hero.id]">
<button style ="min-height: 70px" (click)="gotoClick(1)">{{hero.name}}</button>
<button style ="min-height: 70px" (click)="gotoClick(2)">{{hero.name}}</button>
<button style ="min-height: 70px" (click)="gotoClick(3)">{{hero.name}}</button>
<button style ="min-height: 70px" (click)="gotoClick(4)">{{hero.name}}</button>
</a>
</div>
dashboard.component.ts
import { Component, OnInit } from '#angular/core';
import { Hero } from '../hero.class';
import { HeroService } from '../hero.service';
import { StepService } from '../step.service';
#Component({
moduleId: module.id,
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
heroes: Hero[] = [];
constructor(private heroService: HeroService, private _stepService: StepService, private _teststepService: StepService) { }
ngOnInit() {
this.heroService.getHeroes().subscribe(heroes => this.heroes = heroes);
}
private test: number;
gotoClick(value: number){
this._stepService.setTest(value);
this._teststepService.apiURL();
}
}
hero.service.ts
import { Injectable } from '#angular/core';
import { Headers, Http, Response } from '#angular/http';
import { Hero } from './hero.class';
import { Observable } from "rxjs/Rx";
#Injectable()
export class HeroService {
private headers = new Headers({'Content-Type': 'application/json'});
private heroesUrl = 'api/heroes'; // URL to web api
constructor(private http: Http){ }
getHeroes(): Observable<Hero[]> {
return this.http.get(this.heroesUrl)
.map(response => response.json().data as Hero[]);
}
getHero(id: number): Observable<Hero> {
const url = `${this.heroesUrl}/${id}`;
return this.http.get(url)
.map(response => response.json().data as Hero);
}
}
You can use the built-in index property of *ngFor:
<div class="grid grid-pad">
<a *ngFor="let hero of heroes; let i = index;" [routerLink]="['/detail', hero.id]">
<button style ="min-height: 70px" (click)="gotoClick(i)">{{hero?.name}</button>
</a>
</div>
Documentation: https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html
I have to do a mobile application for school and I choosed to use Ionic 2 for this.
I need to display the daily timetable/schedule. For this, I'm using our intranet's API which returns a json, for exemple :
{
"1": [],
"4": {
"matiere": "M4201",
"prof": "LANDRÉ Jérôme",
"salle": "H201",
"evaluation": "N",
"texte": null,
"commentaire": null,
"type": "td",
"fin": 7
},
"7": {
"matiere": "M4204",
"prof": "GOMMERY Patrice",
"salle": "H205",
"evaluation": "N",
"texte": null,
"commentaire": null,
"type": "tp",
"fin": 10
},
"13": {
"matiere": "",
"prof": "",
"salle": "****",
"evaluation": "N",
"texte": "PROJETS",
"commentaire": null,
"type": "CM",
"fin": 19
},
"16": [],
"19": [],
"22": []
}
I successfully retrieve this in my application, but I dont find how to display of list of this.
Here is my /home/home.ts script :
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Home } from '../../models/home';
import { HomeCours } from '../../providers/home-cours';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
cours: Home[]
constructor(public navCtrl: NavController, private HomeCours: HomeCours) {
HomeCours.load().subscribe(cours => {
console.log(cours)
})
}
}
My /models/home.ts :
/**
* Created by corentin on 17/03/2017.
*/
//récupère la liste des cours sur http://intranet.iut-troyes.univ-reims.fr/api/edtjour/< id de la personne qui consulte >
export interface Home {
matiere: string;
prof: string;
salle: string;
evaluation: string;
texte: string;
commentaire: string;
type: string;
fin: number;
}
My /providers/home-cours.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import { Home } from '../models/home';
/*
Generated class for the HomeCours provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
#Injectable()
export class HomeCours {
coursApiUrl = 'https://api.corentincloss.fr/intranet/edt.php?id=';
constructor(public http: Http) {
console.log('Hello HomeCours Provider');
}
load(): Observable<Home[]> {
return this.http.get(`${this.coursApiUrl}closs006`).map(res => <Home[]>res.json());
}
}
and finally my home.html :
<ion-header>
<ion-navbar>
<ion-title>Mes cours</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<h2>Emploi du temps du jour.</h2>
<hr />
<ion-list>
<div ion-item *ngFor="let cour of cours">
<h2>{{ cour.matiere }}</h2>
</div>
</ion-list>
</ion-content>
I'm sure this is coming from the id ("1", "4", "7"...) but I don't find any way to search the datas in those arrays.
If you could help me please it would be great :D
Thank you :)
After you've obtained the data, you should assign it to a property in your class:
export class HomePage {
cours: Home[]
constructor(public navCtrl: NavController, private HomeCours: HomeCours) {
HomeCours.load().subscribe(cours => this.cours = cours);
}
}
You can't *ngFor object. You should make an array from object.
export class HomePage {
cours: Home[] = []
constructor(public navCtrl: NavController, private HomeCours: HomeCours) {
HomeCours.load().subscribe((data: any) => for (let key in data) this.cours.push({key: key, value: cours[key]}););
}
}
Finally found, I had to declare a new array named "cours".
Here is my cours.ts :
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { CoursService } from '../../providers/cours-service';
/*
Generated class for the Cours page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
#Component({
selector: 'page-cours',
templateUrl: 'cours.html',
providers: [CoursService]
})
export class CoursPage {
public cours: any;
public heures: any;
constructor(public navCtrl: NavController, public navParams: NavParams, public coursService: CoursService) {
this.loadCours();
console.log(coursService);
}
loadCours(){
this.coursService.load()
.then(data => {
let cours = new Array();
for (let key in data) {
cours.push(data[key]);
}
this.cours = cours;
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad CoursPage');
}
}
And now it's perfectly working ! Thank you for your answers :)
This is the first component where i am pushing those things into array named items and i am trying to get it in the second component through service
import { Component } from '#angular/core';
import { FormBuilder, FormControl } from '#angular/forms';
import {AppService} from '../second/app.service';
import { Router } from '#angular/router';
import { Http,Response } from '#angular/http';
import { routing, appRoutingProviders } from '../app.route';
import { Validators } from '#angular/forms';
import {BrowserModule} from '#angular/platform-browser';
#Component({
selector: 'first-app',
templateUrl:"../app/src/component/first/app.firstpage.html"
})
export class FirstComponent
{
data:any;
public items=[];
public edited=false;
public city=false;
public dateCon=false;
inputForm: FormGroup;
Select: FormControl;
Selectt: FormControl;
dat:FormControl;
constructor(private appservice:AppService,builder: FormBuilder, router:Router)
{
this.appservice.getData().subscribe(res=>{this.data=res.json()});
console.log(this.data);
this.Select = new FormControl('', [
Validators.required
]);
this.Selectt = new FormControl('', [
Validators.required
]);
this.dat = new FormControl('', [
Validators.required
]);
this.inputForm = builder.group({
Select: this.Select,
Selectt: this.Selectt,
dat: this.dat
});
this.router=router;
this.appservice=appservice;
}
ngOnInit(){
this.appservice.getData()
}
onclick(a,b) {
console.log(this.data);
let sel1=this.inputForm.value.Select;
let sel2=this.inputForm.value.Selectt;
let sel3=this.inputForm.value.dat;
console.log(sel3);
console.log(sel1);
console.log(sel2);
console.log(this.data.bus.length);
for(let i=0;i<this.data.bus.length;i++){
if((this.data.bus[i].from==sel1)&&(this.data.bus[i].to==sel2))
{
this.items.push(this.data.bus[i]);
}
}
this.appservice.setData(this.items);
}
if((sel1!="")&&(sel2!="")&&(sel3!="")&&(sel1!=sel2))
{
this.router.navigate(['/sec-component']);
}
else if((sel1=="")&&(sel2=="")&&(sel3==""))
{
this.edited=true;
}
if((sel1==sel2)&&((sel1!="")&&(sel2!="")))
{
this.edited=false;
this.city=true;
}
else
{
this.city=false;
}
if(sel1!=sel2)
{
this.edited=false;
}
if(sel3=="")
{
this.dateCon=true;
}
else
{
this.dateCon=false;
}
}
}
This is the second component to which i am passing this array and i need to get that printed over there and each properties to be accessed rather than the entire stuff.
import { Component } from '#angular/core';
import {AppService} from '../first/first.service';
#Component({
template:
`
<h1>second component</h1>
<h1>second component</h1>
<p >{{myName}}</p>
`
})
export class SecondComponent {
constructor(private appservice: AppService)
{
this.appservice=appservice;
this.myName=appservice.getVal();
}
}
This is the service page where i am returning the values
import {Component, Injectable,Input,Output,EventEmitter} from '#angular/core'
import { Http, Response } from '#angular/http';
export interface myData
{
name:any;
}
#Injectable()
export class AppService
{
sharingData: myData={name:""};
constructor(private http:Http){ }
getData()
{
return this.http.get('./app/src/component/busDet.json')
}
setData(i)
{
console.log('save data function called' + i + this.sharingData.name);
this.sharingData.name=i;
console.log(this.sharingData.name);
}
getVal()
{
console.log(this.sharingData.name);
return this.sharingData.name;
}
}
I am getting the output as object.object
I am not able to get the values with in the JSON in the next component.