Ionic 2: How to call Provider function in Controller class - ionic2

I have created new Cordova Plugin only on my machine. Then I added it to my project. It is working fine when I call that plugin. Now, I tried to make a structured caller for my plugin. I created a Provider for it, but the problem is I don't know how to call my plugin function from my Controller class. Below is my sample code.
Provider: my-service.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
declare let myPlugin: any;
#Injectable()
export class MyService {
constructor(public http: Http) {
console.log('Hello MyService Provider');
}
public myFunction() {
myPlugin.myPluginFunction(
(data) => {
return data;
},
(err) => {
return err;
});
}
}
Pages: my-page.ts
import { Component } from '#angular/core';
import { NavController, ViewController } from 'ionic-angular';
import { MyService } from '../../providers/my-service';
#Component({
selector: 'page-my-page-ionic',
templateUrl: 'hello-ionic.html'
})
export class MyPage {
constructor(private viewCtrl: ViewController, private myService: MyService) {}
ionViewWillEnter() {
//I tried to call like this
this.myService.myFunction().subscribe(
data => {
alert("success");
},
error => {
alert("error");
});
}
}
It returns me this error - Property 'subscribe' does not exist on type 'void'. I don't know how to call that function, since my provider returns me success or error.

I think since your myFunction() does not return any observable you cannot subscribe to it. It just returns data directly.
You can use it like this in this case:
var data = this.myService.myFunction();
console.log("Data from plugin is :", data);
If you want to use it as an Observable, return a new observable like this:
public myFunction() {
return Observable.create(observer => {
myPlugin.myPluginFunction(
(data) => {
observer.next(data);
},
(err) => {
observer.next(data);
});
},
(err) => {
observer.error(err);
});
}

Related

Angular app keeps saying message does not exist

I'm building a chat app with Angular and Django using the get stream tutorial. https://getstream.io/blog/realtime-chat-django-angular/
However, I'm trying to run the app to create the chat view but it keeps saying 'messages' does not exist at the point marked 'this point' in the code.
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { MessageResponse, Channel } from 'stream-chat';
import { StreamService } from '../stream.service';
import { StateService } from '../state.service';
declare const feather: any;
#Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.scss'],
})
export class ChatComponent implements OnInit {
constructor(
public streamService: StreamService,
private stateService: StateService,
private router: Router
) {}
messages: MessageResponse[] = [];
message = '';
channel!: Channel;
async sendMessage() {
if (this.message) {
try {
await this.channel.sendMessage({
text: this.message,
});
this.message = '';
} catch (err) {
console.log(err);
}
}
}
getClasses(userId: string): { outgoing: boolean; incoming: boolean } {
const userIdMatches = userId === this.streamService.currentUser.messages.id; (this point)
return {
outgoing: userIdMatches,
incoming: !userIdMatches,
};
}
}

Ionic 2: Error testing with Karma/Jasmine/TestBed

I'm new with Ionic2 and I was following this tutorial and a simple test like
describe('Dummy test', () => {
it('should do nothing', () => {
expect(true).toBeTruthy();
expect(1 + 1).toBe(2);
});
});
works fine, but for some reason I keep getting this error when I try to follow the rest of the tutorial.
Component: Root Component
✖ initialises with a root page of LoginPage
Firefox 45.0.0 (Linux 0.0.0)
TypeError: win is undefined in src/test.ts (line 937)
My src/test.ts is the same as the tutorial and it doesn't have any win in it. My app.spec.ts is this
import { TestBed, ComponentFixture, async } from '#angular/core/testing';
import { IonicModule } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { UserData } from '../providers/user-data';
import { LoginPage } from '../pages/login/login';
import { Platform } from 'ionic-angular';
import { MyApp } from './app.component';
import { LoginPage } from '../pages/login/login';
let comp: MyApp;
let fixture: ComponentFixture<MyApp>;
describe('Component: Root Component', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyApp],
providers: [
StatusBar,
SplashScreen,
UserData,
Platform
],
imports: [
IonicModule.forRoot(MyApp)
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyApp);
comp = fixture.componentInstance;
});
afterEach(() => {
fixture.destroy();
comp = null;
});
it('initialises with a root page of LoginPage', () => {
expect(comp['rootPage']).toBe(LoginPage);
});
});
And my app.component.ts is this
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 { MenuSidePage } from '../pages/menu-side/menu-side';
import { LoginPage } from '../pages/login/login';
import { UserData } from '../providers/user-data';
#Component({
template: `<ion-nav #nav [root]="rootPage"></ion-nav>`
})
export class MyApp {
rootPage: any;
constructor(
public platform: Platform,
public statusBar: StatusBar,
public splashScreen: SplashScreen,
private userData: UserData,
) {
platform
.ready()
.then(() => {
//First - check if user is logged
if(this.userData.currentUser) {
this.rootPage = MenuSidePage;
} else {
this.rootPage = LoginPage;
}
statusBar.styleDefault();
splashScreen.hide();
});
}
}
I don't have yet the solution, but you shouldn't use compileComponents() 'cause you are using a template and not a templateUrl like said in this tutorial :
"We need to use compileComponents when we need to asynchronously compile a component, such as one that has an external template (one that is loaded through templateUrl and isn’t inlined with template). This is why the beforeEach block that this code runs in uses an async parameter – it sets up an asynchronous test zone for the compileComponents to run inside."
Hope it's a kind of helping :)
The win() function come from the Plaftorm, you have to mock it as follow :
export class PlatformMock {
public ready(): Promise<string> {
return new Promise((resolve) => {
resolve('READY');
});
}
public getQueryParam() {
return true;
}
public registerBackButtonAction(fn: Function, priority?: number): Function {
return (() => true);
}
public hasFocus(ele: HTMLElement): boolean {
return true;
}
public doc(): HTMLDocument {
return document;
}
public is(): boolean {
return true;
}
public getElementComputedStyle(container: any): any {
return {
paddingLeft: '10',
paddingTop: '10',
paddingRight: '10',
paddingBottom: '10',
};
}
public onResize(callback: any) {
return callback;
}
public registerListener(ele: any, eventName: string, callback: any): Function {
return (() => true);
}
public win(): Window {
return window;
}
public raf(callback: any): number {
return 1;
}
public timeout(callback: any, timer: number): any {
return setTimeout(callback, timer);
}
public cancelTimeout(id: any) {
// do nothing
}
public getActiveElement(): any {
return document['activeElement'];
}
}
Here is the link to see a project for real integration of this mock class.
Hope it helps :)

angular2 - cannot get data from web service

Learning typescript & angular2 for the first time. I'm creating a generic service that just does GET and POST so that I can use it in the entire app. I've based my app on Angular's example from Dynamic Forms
My issue is that my "QuestionService" is using a "ServerService" but it is complaining that this.ServerService.getData is not a function isnt a function.
ServerService
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
#Injectable()
export class ServerService {
private apiUrl = 'app/users.json';
constructor (private http: Http) {}
getData (): Observable<any>[] {
return this.http.get(this.apiUrl)
.map(this.extractData)
.catch(this.handleError);
}
QuestionService
import { ServerService } from './server.service';
#Injectable()
export class QuestionService implements OnInit{
errorMessage: string;
mode = 'Observable';
questions: QuestionBase<any>[];
ServerService = ServerService;
ngOnInit() { this.getQuestions(); }
getQuestions(ServerService: ServerService<any>){
console.log('getQuestions');
console.log(this.ServerService.getData());
this.ServerService.getData()
.subscribe(
questions => this.questions = questions,
error => this.errorMessage = <any>error);
}
Here is the url: https://plnkr.co/edit/InWESfa6PPVKE0rXcSFG?p=preview
What you need to do is let Angular inject the ServerService into the QuestionService, just like are doing with the Http inside the ServerService
#Injectable()
export class QuestionService implements OnInit{
constructor(private serverService: ServerService) {}
ngOnInit() { this.getQuestions(); }
getQuestions(){
this.serverService.getData()
.subscribe(
questions => this.questions = questions,
error => this.errorMessage = <any>error);
}
}
Then you need to add both services to the providers array
#NgModule({
imports: [HttpModule],
providers: [ServerService, QuestionService]
})
export class AppModule {}

angular 2 RC4- Cannot resolve all parameters for 'Router'

I have written a test for my component and it is failing with
Error: Cannot resolve all parameters for 'Router'(?, ?, ?, ?, ?, ?,
?). Make sure that all the parameters are decorated with Inject or
have valid type annotations and that 'Router' is decorated with
Injectable.
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { Supplier } from './supplier';
import { SupplierService } from './supplier.service';
import { AppService } from '../shared/app.service';
#Component({
moduleId: module.id,
selector: 'supplier-form',
templateUrl: './supplier-form.component.html',
styleUrls: ['./supplier-form.component.css']
})
export class SupplierFormComponent implements OnInit {
private countries: any;
private model: Supplier;
private errorMessage: string;
private submitted: boolean = false;
private active: boolean = true;
constructor(private appService: AppService, private supplierService: SupplierService, private router: Router, private route: ActivatedRoute) {
this.model = new Supplier();
this.route.params.subscribe(params => {
let id = +params['id']; // (+) converts string 'id' to a number
if (!isNaN(id))
this.supplierService.getSupplierById(id)
.subscribe(supplier => this.model = supplier, error => this.errorMessage = error);
});
}
ngOnInit() {
this.getCountries();
}
private getCountries() {
this.appService.getCountry()
.subscribe(countries => this.countries = countries.items,
error => this.errorMessage = error);
}
private navigateToHomePage(supplier) {
if (supplier) {
let link = [''];
this.router.navigate(link);
}
}
private onSubmit(): void {
this.submitted = true;
this.supplierService.saveSupplier(this.model).subscribe(
supplier => this.navigateToHomePage(supplier),
error => this.errorMessage = error);
}
}
very simple component all its doing is getting countries from a service which is using Http call and calling save method on another service which is also http call. I am mocking those services with my Mock classes. below is my test code.
import { By } from '#angular/platform-browser';
import { DebugElement, provide } from '#angular/core';
import { disableDeprecatedForms, provideForms } from '#angular/forms';
import { Router, ActivatedRoute } from '#angular/router';
import * as Rx from 'rxjs/Rx';
import {
beforeEach, beforeEachProviders,
describe, xdescribe,
expect, it, xit,
async, inject, addProviders,
TestComponentBuilder, ComponentFixture
} from '#angular/core/testing';
import { SupplierFormComponent } from './supplier-form.component';
import { SupplierService } from './supplier.service';
import { AppService } from '../shared/app.service';
describe('Component: Supplier', () => {
var builder;
beforeEachProviders(() => {
return [
disableDeprecatedForms(),
provideForms(),
Router, ActivatedRoute,
provide(AppService, { useClass: MockAppService }),
provide(SupplierService, { useClass: MockSupplierService })
];
});
beforeEach(inject([TestComponentBuilder], (tcb) => {
builder = tcb;
}));
it('should create Supplier Component', async(() => {
/*.overrideProviders(
SupplierFormComponent,
[{ provide: AppService, useClass: MockAppService }]
)*/
builder.createAsync(SupplierFormComponent)
.then((fixture: ComponentFixture<SupplierFormComponent>) => {
fixture.detectChanges
var compiled = fixture.debugElement.nativeElement;
console.log(compiled);
})
.catch((error) => {
console.log("error occured: " + error);
});
}));
});
class MockAppService {
public name = "Injected App Service";
public fakeResponse: any = [{ "id": 1, "name": "uk" }];
public getCountry() {
return this.fakeResponse;
}
}
class MockSupplierService {
public name = "Injected Supplier Service";
saveSupplier(supplier: any): boolean {
return true;
}
}
any idea how can i mock router properly with RC.4.

How to mock AngularFire 2 service in unit test?

I'm trying to set up unit tests for a sample Angular 2 app using AngularFire 2 auth, the component is fairly simple:
import { Component } from '#angular/core';
import { AngularFire, AuthProviders } from 'angularfire2';
#Component({
moduleId: module.id,
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent {
isLoggedIn: boolean;
constructor(public af: AngularFire) {
this.af.auth.subscribe(auth => {
if (auth) {
this.isLoggedIn = true;
} else {
this.isLoggedIn = false;
}
});
}
loginWithFacebook() {
this.af.auth.login({
provider: AuthProviders.Facebook
});
}
logout() {
this.af.auth.logout();
}
}
All I'm doing is wrapping around the login and logout methods in AngularFire so I was thinking about using a mock to check if the methods were called but I'm not sure where to start, I tried doing the following in my spec file:
import { provide } from '#angular/core';
import { AngularFire } from 'angularfire2';
import {
beforeEach, beforeEachProviders,
describe, xdescribe,
expect, it, xit,
async, inject
} from '#angular/core/testing';
import { AppComponent } from './app.component';
spyOn(AngularFire, 'auth');
beforeEachProviders(() => [
AppComponent,
AngularFire
]);
describe('App Component', () => {
it('should create the app',
inject([AppComponent], (app: AppComponent) => {
expect(app).toBeTruthy();
})
);
it('should log user in',
inject([AppComponent], (app: AppComponent) => {
expect(app.fb.auth.login).toHaveBeenCalled();
})
);
it('should log user out',
inject([AppComponent], (app: AppComponent) => {
expect(app.fb.auth.logout).toHaveBeenCalled();
})
);
});
However I'm not sure how to mock the login and logout methods since they're part of the auth property, is there a way to mock auth and also the returning login and logout methods?
In this snippet:
beforeEach(() => addProviders([
AppComponent,
AngularFire
]);
You set (or override) the providers that will be used in your test.
That being said, you can create a different class, a mock if you will, and, using the { provide: originalClass, useClass: fakeClass } notation, provide it instead of the AngularFire actual class.
Something like this:
class AngularFireAuthMock extends AngularFireAuth { // added this class
public login() { ... }
public logout() { ... }
}
class AngularFireMock extends AngularFire { // added this class
public auth: AngularFireAuthMock;
}
beforeEach(() => addProviders([
AppComponent,
{ provide: AngularFire, useClass: AngularFireMock } // changed this line
]);
And the AngularFires in your tests will be AngularFireMocks.
hope it is not off the topic, but the easiest solution I have found how to mock the FirebaseDatabase.
var object = function() {
var obj = { valueChanges() {
return of({data:'data'});
}
}
return obj;
}
providers: [..., { provide : AngularFireDatabase,
useValue: {object : object }} ]
instead of data:'data' you can mock whatever data you need. The functions can be modified as you wish.
Similar to #jan, I made a mock using some utility functions:
import {AngularFireAuth} from '#angular/fire/auth';
import {AngularFireDatabase} from '#angular/fire/database';
import {auth} from 'firebase/app';
import { Observable, of, Subscription } from 'rxjs';
/**
* Mocks the Firebase auth by automatically logging in.
*/
export const AngularFireAuthMock = jasmine.createSpy('signInWithEmailAndPassword')
.and.returnValue(Promise.resolve({uid: 'fakeuser'}));
/**
* Mocks an AngularFireDatabase that always returns the given data for any path.
*/
export function mockAngularFireDatabase(data): AngularFireDatabase {
return {
object: (path: string): any => {
return {
valueChanges() {
return of(data);
}
}
}
} as AngularFireDatabase;
}
and then you can use them in your spec like this:
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ TweakComponent ],
imports: [ MatDialogModule, RouterTestingModule ],
providers: [
{ provide: MAT_DIALOG_DATA, useValue: {} },
{ provide: AngularFireDatabase, useValue: mockAngularFireDatabase({testdata:'hi'})},
{ provide: AngularFireAuth, useValue: AngularFireAuthMock}
],
})
.compileComponents();
});