How to use the Capacitor Browser API - ionic4

I am currently porting my project to Ionic 4 and wanted to replace the Cordova InAppBrowser with the Capacitor browser but with little success so far...
This is my page:
import { Component, OnInit } from '#angular/core';
import {Plugins} from '#capacitor/core';
const { Browser } = Plugins;
#Component({
selector: 'app-srd',
templateUrl: './srd.page.html',
styleUrls: ['./srd.page.scss'],
})
export class SrdPage implements OnInit {
constructor() {
}
async ngOnInit() {
const url = 'http://capacitor.ionicframework.com/';
await Browser.open({'url': url});
}
}
There is no console output and the page stays blank.
Any ideas what went wrong?

This should work.
Remove the quote around the first url:
import { Component, OnInit } from '#angular/core';
import {Plugins} from '#capacitor/core';
const { Browser } = Plugins;
#Component({
selector: 'app-srd',
templateUrl: './srd.page.html',
styleUrls: ['./srd.page.scss'],
})
export class SrdPage implements OnInit {
constructor() {
}
async ngOnInit() {
const url = 'http://capacitor.ionicframework.com/';
await Browser.open({'url': url});
}
}

import { Browser } from '#capacitor/browser';
async openLink(Url){
await Browser.open({ url: Url });
}

const url = 'http://capacitor.ionicframework.com/';
await Browser.open({url: url});

Related

Cannot read property 'setFocus' of undefined in ion-searchbar (ionic 4)

I having the problem of cannot read property setFocus of undefined in ion-searchbar (ionic 5).
when I display console log. Hope some one will help me.
In my HTML
<ion-toolbar *ngIf="showSearchbar">
<ion-searchbar [(ngModel)]="searchTerm" #autofocus (ionChange)="setFilteredItems()">
</ion-searchbar>
</ion-toolbar>
In my ts file.
import { Component, ViewChild } from '#angular/core';
import { IonSearchbar } from '#ionic/angular';
#ViewChild('autofocus', { static: false }) searchbar: IonSearchbar;
ngOnInit(){ setTimeout(() => this.searchbar.setFocus(), 500); }
You can do the following:
home.page.html
<ion-searchbar #searchbar debounce="500" [(ngModel)]="searchParam"></ion-searchbar>
home.page.ts
import { Component, OnInit, ViewChild } from '#angular/core';
import { IonSearchbar } from '#ionic/angular';
#Component({
selector: 'app-home',
templateUrl: './home.page.html',
styleUrls: ['./home.page.scss'],
})
export class HomePage implements OnInit {
#ViewChild('searchbar', { static: false, read: IonSearchbar }) searchbar: IonSearchbar;
public searchParam = ''
constructor() { }
OnInit() { }
ionViewDidEnter() {
this.searchbar?.setFocus()
}
}
By using this.searchbar?.setFocus() in ionViewDidEnter lifecycle, the searchbar element will have focus each time the page component is loaded. You can use other lifecycles like ionViewWillEnter. Read more about ionic angular lifecycles here: https://ionicframework.com/docs/angular/lifecycle
And other ion-searchbar methods: https://ionicframework.com/docs/api/searchbar#methods
Try to use something like this:
ionViewWillEnter(){
this.searchbar.setFocus()
}
and read this: https://ionicframework.com/docs/angular/lifecycle

Unable to get data when making httpClient.get in angular 5

I am trying to do a http.get using httpclient. However, and i am getting
ReferenceError: data is not defined
Inside my component class when subscribing to service method.
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
const httpOptions = {
headers: new HttpHeaders()
.set('Authorization', 'Bearer xxxxx')
.set('Content-Type', 'application/json')
};
#Injectable()
export class SetsService {
constructor(private http: HttpClient) { }
getSet() {
return this.http.get('http://localhost:1234/api/users', httpOptions);
}
}
my component
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { Router } from '#angular/router';
import { SetsService } from '../services/sets.service';
import { Observable } from 'rxjs/Observable';
#Component({
selector: 'app-sets',
templateUrl: './sets.component.html',
styleUrls: ['./sets.component.scss']
})
export class SetsComponent implements OnInit {
id: string = "";
set: any = {};
constructor(private route: ActivatedRoute, private router: Router, private _setsService: SetsService) {
this.route.params.subscribe(res => this.id = res.id);
}
ngOnInit() {
this.getSets();
}
getSets(){
this._setsService.getSet().subscribe(
(data) => { this.set = data },
err => console.error(err),
() => { console.log('done loading set') }
);
}}
When i look at the network the API call is successful and returning data.
Inside the html I am simply trying to print the set object.

Creating restricted members area in Angular Fire 2

I am trying to make an application using angularfire 2. Can't find the perfect way to make the members area restricted that means only authenticated members can access that area. Here is my 'login.component.ts' file
import { Component, OnInit, HostBinding } from '#angular/core';
import { AngularFire, AuthProviders, AuthMethods } from 'angularfire2';
import { FormControl, FormGroup, Validators } from '#angular/forms';
import { Router } from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
})
export class LoginComponent {
state: string = '';
error: any;
login: FormGroup;
constructor(
public af: AngularFire,
private router: Router
) {
//official angfire 2 app example
//this.af.auth.subscribe(auth => console.log(auth));
}
ngOnInit() {
this.login = new FormGroup({
username: new FormControl('', Validators.required),
password: new FormControl('', Validators.required)
});
}
onSubmit() {
//console.log(this.login.value, this.login.valid);
var value = this.login.value;
//console.log(value.username);
//console.log(value.password);
this.af.auth.login({
email: value.username,
password: value.password,
},
{
provider: AuthProviders.Password,
method: AuthMethods.Password,
}).then(
(success) => {
console.log(success);
this.router.navigate(['/members']);
}).catch(
(err) => {
console.log(err);
this.error = err;
})
}
}
and the members.component.ts file
import { Component, OnInit } from '#angular/core';
import { AngularFire, AuthProviders, AuthMethods } from 'angularfire2';
import { Router } from '#angular/router';
#Component({
selector: 'app-other',
templateUrl: './members.component.html',
styleUrls: ['./members.component.css']
})
export class MembersComponent implements OnInit {
//name: "";
//state: string = '';
constructor(
public af: AngularFire,
private router: Router
) {
this.af.auth.subscribe(auth => {
if(auth) {
console.log(auth);
}
});
}
logout() {
this.af.auth.logout();
console.log('logged out');
this.router.navigate(['/login']);
}
ngOnInit() {
}
}
I know my code may be seem like a dumb one but actually I am trying to study over this. But there is not enough documentation to solve my problem I guess. Thanks in advance.
https://coursetro.com/posts/code/32/Create-a-Full-Angular-Authentication-System-with-Firebase
this is a great tutorial that solves your problem

How to use extends for this angulr2 scenario?

In my application core component is root component, In this page header , sidemenu designs are existed,
SideMenu is dynamic, so I write logic of the code in other sidemenu component,
Now I want to use the functionality of sidemenu in core component, I think it is
done by using extends,
My componets are
core component
import { Component, OnInit } from '#angular/core';
import {SidemenuComponent} from './sidemenu.component';
#Component({
selector: 'my-admin',
templateUrl: '../views/admin-header.html'
})
export class CoreComponent extends SidemenuComponent {
constructor( private router: Router) {
}
}
sidemenucomponent
import {OnInit } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';
import {MenuService} from './core.service';
export class SidemenuComponent implements OnInit{
userroleId : any;
roleName: string;
menuItems:any;
constructor(private http: Http,private MenuService:MenuService) {
this.userroleId = localStorage.getItem("roleId")
}
ngOnInit(): void {
this.getSideMenu();
}
getSideMenu () {
if( this.userroleId == 1) {
this.MenuService.getAdminMenu().subscribe(menuItems => this.menuItems= menuItems, error => console.log(error));
}
if(this.userroleId == 2){
this.MenuService.getpractitionerMenu().subscribe(menuItems => this.menuItems= menuItems, error => console.log(error));
console.log('ss')
}
}
}
MenuService
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class MenuService {
constructor(private http: Http) {}
public getAdminMenu(): Observable<any> {
return this.http.get("./app/core/adminsidemenu.json")
.map((res:any) => res.json())
.catch(this.handleError);
}
public getpractitionerMenu(): Observable<any> {
return this.http.get("./app/core/practitioner.json")
.map((res:any) => res.json())
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
Here I am unable extends the sidemenu component in core component.
I am getting error in my console:
Constructors for derived classes must contain a 'super' call.
Please help me
It appears you may be missing the #Component decorator on the SidemenuComponent.
Here's a Plunker with a simple extended Component, and here's a good article on it: Component Ineritance.
You need to call the constructor of the parent class in your child-class:
#Component({
selector: 'my-admin',
templateUrl: '../views/admin-header.html'
})
export class CoreComponent extends SidemenuComponent {
constructor( private router: Router, http: Http, menuService:MenuService) {
super(http,menuService);
}
}

Angular 2 – No data afte api call

I am playing around with angular 2 and the heroes tutorial. The Problem is that I always get an empty object no matter which api I call.
Here is the code:
app.compomnent.ts
import { Component, OnInit } from '#angular/core';
import { Http, Response } from '#angular/http';
// Add the RxJS Observable operators we need in this app.
import './rxjs-operators';
#Component({
selector: 'my-app',
template: `
<h1>Test</h1>
`
})
export class AppComponent implements OnInit {
constructor(private http: Http) {}
private error: any;
ngOnInit() {
var request = this.http.get('http://date.jsontest.com');
console.log("Request: " + request);
console.log("Map: " + request.map(res => res));
console.log("Complete: " + this.http.get('http://date.jsontest.com')
.map(res => res.json())
.catch(this.error));
}
}
main.ts:
// The usual bootstrapping imports
import { bootstrap } from '#angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '#angular/http';
import { AppComponent } from './app.component';
bootstrap(AppComponent, [
HTTP_PROVIDERS
]);
The result in my console:
An Observable doesn't do anything until you subscribe to it because they are lazy
ngOnInit() {
this.http.get('http://date.jsontest.com')
.map(res => res.json())
.subscribe(
data => this.data = data,
() => console.log('done'),
err => this.error(err));
}