Here i create two ts file one is service another is General in service i implement some service and calling in General ts file while my page getting load its throughing Error as at NoProviderError.BaseError [as constructor]
Service.ts
#Component({
templateUrl: "../../template/customer/customer.html",
providers: [CustomerService]
})
Url = "http://localhost:54873/Api/Home/GetEmp"
public constructor(private _http: Http) {
}
getEmpData() {
debugger;
return this._http.get(this.Url).map(this.extractData).catch(this.handleError);
}
Component.ts
#Component({
templateUrl: "../../template/customer/customer.html",
providers: [CustomerService]
})
#Injectable()
export class CustomerComponent {
Url = "http://localhost:54873/Api/Home/GetEmp"
getfun: string;
constructor(private _HttpService: CustomerService) { }
getData() {
return this._HttpService.getEmpData().subscribe(data => this.getfun = JSON.stringify(data), error => alert('This is error...'),
() => console.log());
}
You cannot have #Component inside a service.ts file, it should be as follows,
#Injectable()
export class CustomerService {
public constructor(private _http: Http) {
}
getEmpData(): Observable<Employee[]> {
debugger;
return this._http.get(this.Url).map(this.extractData).catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
// this.Employees = res.json
return body.data || {};
}
private handleError(error: Response | any) {
// In a real world app, you might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
Related
PeerJS: 1.3.2
Tested on: iOS 15 & 13.
I have the below call service file that implements PeerJS functionality to init, establish and answer video calls.
Calls work as expected across Android devices, macOS and PCs.
However, when attempting to join from an iOS device, we see the following error raised:
NotAllowedError: The request is not allowed by the user agent
or the platform in the current context, possibly because the
user denied permission.
call-service.js:
import { Injectable } from '#angular/core';
import { MatSnackBar } from '#angular/material/snack-bar';
import Peer from 'peerjs';
import { BehaviorSubject, Subject } from 'rxjs';
import { v4 as uuidv4 } from 'uuid';
#Injectable()
export class CallService {
private peer: Peer;
private mediaCall: Peer.MediaConnection;
private localStreamBs: BehaviorSubject<MediaStream> = new BehaviorSubject(null);
public localStream$ = this.localStreamBs.asObservable();
private remoteStreamBs: BehaviorSubject<MediaStream> = new BehaviorSubject(null);
public remoteStream$ = this.remoteStreamBs.asObservable();
private isCallStartedBs = new Subject<boolean>();
public isCallStarted$ = this.isCallStartedBs.asObservable();
constructor(private snackBar: MatSnackBar) { }
public initPeer(): string {
if (!this.peer || this.peer.disconnected) {
const peerJsOptions: Peer.PeerJSOption = {
debug: 3,
config: {
iceServers: [
{
urls: [
'stun:stun1.l.google.com:19302',
'stun:stun2.l.google.com:19302',
],
}]
}
};
try {
let id = uuidv4();
this.peer = new Peer(id, peerJsOptions);
return id;
} catch (error) {
console.error(error);
}
}
}
public async establishMediaCall(remotePeerId: string) {
try {
const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true});
let peerOptions: any = {};
if (this.checkSafari()) {
peerOptions.serialization = "json";
}
const connection = this.peer.connect(remotePeerId, peerOptions);
connection.on('error', err => {
console.error(err);
this.snackBar.open(err, 'Close');
});
this.mediaCall = this.peer.call(remotePeerId, stream);
if (!this.mediaCall) {
let errorMessage = 'Unable to connect to remote peer';
this.snackBar.open(errorMessage, 'Close');
throw new Error(errorMessage);
}
this.localStreamBs.next(stream);
this.isCallStartedBs.next(true);
this.mediaCall.on('stream',
(remoteStream) => {
this.remoteStreamBs.next(remoteStream);
});
this.mediaCall.on('error', err => {
this.snackBar.open(err, 'Close');
console.error(err);
this.isCallStartedBs.next(false);
});
this.mediaCall.on('close', () => this.onCallClose());
}
catch (ex) {
console.error(ex);
this.snackBar.open(ex, 'Close');
this.isCallStartedBs.next(false);
}
}
public async enableCallAnswer() {
try {
let peerOptions: any = {};
if (this.checkSafari()) {
peerOptions.serialization = "json";
}
const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
this.localStreamBs.next(stream);
this.peer.on('call', async (call) => {
this.mediaCall = call;
this.isCallStartedBs.next(true);
this.mediaCall.answer(stream);
this.mediaCall.on('stream', (remoteStream) => {
this.remoteStreamBs.next(remoteStream);
});
this.mediaCall.on('error', err => {
this.snackBar.open(err, 'Close');
this.isCallStartedBs.next(false);
console.error(err);
});
this.mediaCall.on('close', () => this.onCallClose());
});
}
catch (ex) {
console.error(ex);
this.snackBar.open(ex, 'Close');
this.isCallStartedBs.next(false);
}
}
private onCallClose() {
this.remoteStreamBs?.value.getTracks().forEach(track => {
track.stop();
});
this.localStreamBs?.value.getTracks().forEach(track => {
track.stop();
});
this.snackBar.open('Call Ended', 'Close');
}
public closeMediaCall() {
this.mediaCall?.close();
if (!this.mediaCall) {
this.onCallClose()
}
this.isCallStartedBs.next(false);
}
public destroyPeer() {
this.mediaCall?.close();
this.peer?.disconnect();
this.peer?.destroy();
}
public checkSafari() {
let seemsChrome = navigator.userAgent.indexOf("Chrome") > -1;
let seemsSafari = navigator.userAgent.indexOf("Safari") > -1;
return seemsSafari && !seemsChrome;
}
}
Closing. This was a local permissions issue on my test device and no fault of PeerJS.
Reinstalling Chrome on iOS then enabled the relevant camera permissions
I use angular 6, firebase and material angular. I can load my data into the table, I can sort them, have the paginator, and filter them globally
I would now like to modify my filter so that it just filters on the 'name' column and have a second filter field to filter on the 'common' column.
Can you help me on the strategy to adopt?
#Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.scss']
})
export class TableComponent implements OnInit {
showSpinner = true;
Data = {nom: '',finessgeo:'', cat1: '', commune: '',CP: '',departement:'',tel: ''}
displayedColumns = ['nom', 'finessgeo', 'cat1', 'commune', 'CP', 'departement', 'tel'];
dataSource = new MatTableDataSource();
applyFilter(filterValue: string) {
filterValue = filterValue.trim();
filterValue = filterValue.toLowerCase();
this.dataSource.filter = filterValue;
}
#ViewChild(MatPaginator) paginator: MatPaginator;
#ViewChild(MatSort) sort: MatSort;
ngAfterViewInit() {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
constructor(public authService: AuthService,private geoService: GeoService, private router: Router,private database: AngularFireDatabase) { }
onNewGeo() {
this.router.navigate(['']);
}
onSignOut() { this.authService.signOutUser(); }
ngOnInit() { return this.geoService.getGeos().subscribe(res =>{this.dataSource.data = res;this.showSpinner = false;}); }}
export class DataDataSource extends DataSource<any> {
constructor(private geoService: GeoService) { super() }
connect() {return this.geoService.getGeos();}
disconnect() {}
}
Try below code:
ngOnInit() {
this.dataSource.filterPredicate = function(data, filter: string): boolean {
return data.name.toLowerCase().includes(filter) || data.nom.toString() === filter;
};
}
Hi I'm trying to write a simple Angular 6 interceptor that adds the jwt token to the header when sending requests.
The problem is that the header in the request arrives NULL on the backend, so of course I can't get the authorization token and I'm having trouble figuring out why.
I'm pretty sure the problem is in my js code because if I try to send the same request via any REST client I can see the header in my Java code just fine.
Here's my js code:
import { Component, OnInit } from '#angular/core';
import {Observable} from 'rxjs/Observable';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { UserService } from './user.service';
#Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
constructor(private http: HttpClient, private userService: UserService) { }
ngOnInit() {
this.userService.getAllUsers().subscribe(
data => {
console.log(data);
/* this.users_from_db=data; */
},
err => {
console.log(err);
}
);
}
users_from_db: Observable<any>;
}
import {Injectable} from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import {Observable} from 'rxjs/Observable';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
#Injectable()
export class UserService {
constructor(private http: HttpClient) {}
public getAllUsers(): Observable<any> {
return this.http.get<any>('http://localhost:8080/users/get-all');
}
}
import { Injectable } from '#angular/core';
import {HttpInterceptor, HttpRequest, HttpHandler, HttpSentEvent, HttpHeaderResponse, HttpProgressEvent,
HttpResponse, HttpUserEvent, HttpErrorResponse} from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Router } from '#angular/router';
import {TokenStorage} from './token.storage';
import 'rxjs/add/operator/do';
const TOKEN_HEADER_KEY = 'Authorization';
#Injectable()
export class Interceptor implements HttpInterceptor {
constructor(private token: TokenStorage, private router: Router) { }
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {
let authReq = req;
if (this.token.getToken() != null) {
console.log("authorizing...");
authReq = req.clone({ headers: req.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + this.token.getToken())});
console.log(authReq);
}
if (!authReq.headers.has('Content-Type')) {
authReq = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
}
return next.handle(authReq).do(
(err: any) => {
if (err instanceof HttpErrorResponse) {
console.log(err);
console.log('req url :: ' + req.url);
if (err.status === 401) {
this.router.navigate(['login']);
}
}
}
);
}
}
The value of the token is surely there when I do this.token.getToken()in the intercept function. I checked by printing the value in the browser console.
Any help is appreciated, thanks.
This is my interceptor:
import { Injectable } from "#angular/core";
import { HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse, HttpInterceptor } from "#angular/common/http";
import { Observable, BehaviorSubject, throwError } from "rxjs";
import { catchError, map, filter, take, switchMap, finalize } from "rxjs/operators";
import { AppConsts } from "../consts";
#Injectable()
export class JwtInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(this.addTokenToRequest(request)).pipe(
map(res => res),
catchError(err => {
if (err instanceof HttpErrorResponse && err.status === 401 && err.headers.has("Token-Expired")) {
// here code to refresh token if needed
} else {
return throwError(err);
}
})
);
}
private addTokenToRequest(request: HttpRequest<any>, token: string = null): HttpRequest<any> {
if (token) {
request = request.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
}
else {
const currentUser = JSON.parse(localStorage.getItem(AppConsts.DEFAULT_USER_STORAGE_NAME));
if (currentUser && currentUser.token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentUser.token}`
}
});
}
}
return request;
}
}
You also can see a simple example - http://jasonwatmore.com/post/2016/08/16/angular-2-jwt-authentication-example-tutorial
I have an Ionic 3 application that calls a Spring Boot API to login into Mobile App,My Spring Boot application is hosted in Aws.It works on android But it doesn't work on ios ,It Says Cross Issue I tried Many Solutions from internet But did not get the result.
The error I am getting is
response with status: 0 for url : null
this is my working spring boot controller
#CrossOrigin
#RestController
#RequestMapping("/api/customerr")
public class loginController extends NamedParameterJdbcDaoSupportClass{
#Autowired
LoginService loginService;
#Autowired
LoginValidation loginValidation;
#RequestMapping(value="/getUser", method = RequestMethod.POST)
public Response getUsers( #RequestBody UserRequest userRequest ) throws Exception {
List<User> users = null;
try {
loginValidation.getUsers(userRequest.getSsoid(), userRequest.getPassword() );
} catch (ValidationExceptions ex) {
ex.printStackTrace();
return new Response("400", ex.getMessage());
}
try {
users = loginService.getUsers(userRequest.getSsoid(),userRequest.getPassword() );
} catch (Exception ex) {
return new Response("400", ex.getMessage());
}
for(User u: users )
{
if(u.getStatus().getStatusId() == 2)
{
return new Response("300", u.getSsoid());
}
}
return new Response("200", users);
}
}
this is my ionic provider/service
import { Http, Response} from '#angular/http';
import { Injectable } from '#angular/core';
#Injectable()
export class loginService {
data:any;
constructor(public http : Http){}
getAllUsers(authData){
alert("api users")
return new Promise(resolve=>{
this.http.post('http://someAddress:8080/api/customerr/getUser', authData)
.map(res=>res.json())
.subscribe(data=>{
this.data=data;
resolve(this.data)
})
})
}
}
This is the login page where I am calling the api
import { Component, ViewChild } from '#angular/core';
import { Alert,AlertController,IonicPage,Loading,LoadingController,NavController,MenuController } from 'ionic-angular';
import { FormBuilder, FormGroup, Validators, NgForm } from '#angular/forms';
import { EmailValidator } from '../../validators/email';
import { CustomerPage } from '../customer/customer';
import { loginService } from '../../providers/loginservice/login.servie';
import {Response} from '#angular/http';
import { ToastController } from 'ionic-angular';
import { CustomerdetailsPage } from '../customerdetails/customerdetails';
#IonicPage()
#Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
#ViewChild('f') loginForm: NgForm;
loginResponse:any;
constructor(
public navCtrl: NavController,
public loadingCtrl: LoadingController,
public alertCtrl: AlertController,
public menu:MenuController,
private loginservice : loginService,
private toastCtrl: ToastController
){
}
ionViewWillEnter(){
this.menu.enable(false)
}
ionViewWillLeave(){
this.menu.enable(true)
}
loginUser() {
console.log("login data");
console.log(this.loginForm.value);
this.loginservice.getAllUsers(this.loginForm.value).then(
(data:any) =>
{
this.loginResponse = data.json();
alert("data");
alert(this.loginResponse.code);
if(this.loginResponse.code === '200')
{
if(this.loginResponse.data.length !== 0)
{
let key1 = 'islogIn';
localStorage.setItem(key1, "true");
this.navCtrl.setRoot(CustomerPage);
}
else if(this.loginResponse.data.length == 0)
{
let toast = this.toastCtrl.create({
message: 'invalid username or password',
duration: 3000,
position: 'bottom'
});
toast.onDidDismiss(() => {
console.log('Dismissed toast');
});
toast.present();
}
}
else if (this.loginResponse.code === '300')
{
let toast = this.toastCtrl.create({
message: 'user is deactivated',
duration: 3000,
position: 'bottom'
});
toast.onDidDismiss(() => {
console.log('Dismissed toast');
});
toast.present();
}
},
(error)=>{
alert(error);
}
);
}
}
And this the app.module.ts
#NgModule({
declarations: [
..
LoginPage,
...
],
imports: [
BrowserModule,
HttpClientModule,
HttpModule,
IonicStorageModule.forRoot(),
IonicModule.forRoot(MyApp),
],
bootstrap: [IonicApp],
entryComponents: [
.
.
LoginPage,
.
.
],
providers: [
Network,
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
Storage,
SocialSharing,
File,
FileOpener,
DatabaseProvider,
SQLitePorter,
SQLite,
GlobalProvider,
PageserviceProvider,
loginService,
syncService
]
})
export class AppModule {}
Please Use Native HTTP API for IOS
https://ionicframework.com/docs/native/http/
I want to access the property 'Status' from the controller and simply do some operations but I am unable to get this property and do any further operation. I am sharing my code below:
TasksController:
[HttpGet]
public ActionResult GetTasks()
{
var q = (from a in db.Tsk
join b in db.TType on a.TaskTypeID equals b.TaskTypeID
join c in db.Prior on a.PriorityID equals c.PriorityID
join d in db.Usr on a.AssignedTo equals d.Employees.EmpName
select new
{
a.TaskID,
a.TaskCode,
a.AssignedTo,
a.Date,
a.DueDate,
a.Status,
a.Reply,
a.PriorityID,
a.TaskTypeID,
b.TaskType,
c.Priorities,
d.Login
}).ToList().Skip(1).AsEnumerable();
db.Configuration.ProxyCreationEnabled = false;
return Json(q, JsonRequestBehavior.AllowGet);
}
AppService:
import { Injectable } from '#angular/core';
import { Http, Headers, Response } from '#angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/filter';
import { Observable } from 'rxjs/Observable'
#Injectable()
export class AppService {
constructor(private _http: Http) { }
//Task Register
getFTRs(c: string) {
return this._http.get('Tasks/GetTasks').map(res => res.json().filter(a => a.Login === c));
}
}
HomeComponent:
import { Component, OnInit, Input } from '#angular/core';
import { AuthenticationService } from '../_services/index';
import { AppService } from '../app.service';
import { LoginComponent } from '../login/index';
import { User, TaskRegisters } from '../contract';
import { Message } from '../message';
#Component({
moduleId: module.id,
selector: 'home',
templateUrl: 'home.component.html',
providers: [LoginComponent]
})
export class HomeComponent implements OnInit {
users: User[];
tasks: string;
msgs: Message[] = [];
curr: any;
constructor(private userService: AuthenticationService,
private Tsk: AppService,
private Log: LoginComponent) { }
ngOnInit() {
debugger;
this.curr = localStorage.getItem('currentUser').slice(1);
this.Tsk.getFTRs(this.curr).subscribe(
res => {
this.tasks = res.Status,
error => console.log(error)
});
if (this.tasks) {
this.msgs.push({ severity: 'error', summary: 'Task Assigned', detail: 'A new task has been assigned to you' })
}
}
}
Status is a boolean and if boolean is true, I want to push the message in msgs array. I am unable to get the value of Status and store it in tasks variable of home component. Whenever I run the program it shows this.tasks as undefined thus making and comparison impossible. Any help will be appreciated.
Change:
this.Tsk.getFTRs(this.curr).subscribe(
res => {
this.tasks = res.Status,
error => console.log(error)
});
if (this.tasks) {
this.msgs.push({ severity: 'error', summary: 'Task Assigned', detail: 'A new task has been assigned to you' })
}
to
this.Tsk.getFTRs(this.curr).subscribe(
(res) => {
console.log(res); //What does this print?
this.tasks = res.Status;
console.log(this.tasks); //What does this print?
if (this.tasks) {
this.msgs.push({ severity: 'error', summary: 'Task Assigned', detail: 'A new task has been assigned to you' })
}
},
(error) => {console.log(error);}
);
Since you're assingning this.tasks inside getFRSs' callback which is async, by the time you are using it below in the if statement it is undefined.
Since this.tasks is available to me now after the edit of #echonax I did this to make it work!
ngOnInit() {
debugger;
this.curr = localStorage.getItem('currentUser').slice(1);
this.Tsk.getFTRs(this.curr).subscribe(
res => {
this.tasks = res;
for (let i = 0; i < this.tasks.length; i++){
if (this.tasks[i].Status) {
this.msgs.push({ severity: 'error', summary: 'Task Assigned', detail: 'A new task has been assigned to you' })
}
}
},
error => console.log(error)
)}