Can't resolve all parameters for File - file

I am trying to implement https://ionicframework.com/docs/native/file-transfer/
Therefor I need to install https://ionicframework.com/docs/native/file/
When I use "File" in my service I get the error:
Can't resolve all parameters for File: (?, ?, ?, ?, ?).
I know that the question marks can resemble a circular reference tough I've never user my service anywhere else, nor did i use "File" before.
import {Injectable} from '#angular/core';
import {File} from "#ionic-native/file";
import { FileTransfer, FileTransferObject } from '#ionic-native/file-transfer';
#Injectable()
export class ImageService {
constructor(private file: File, private transfer: FileTransfer) {
}
public getImagesOfSchedule() {
const fileTransfer: FileTransferObject = this.transfer.create();
const url = 'http://techbooster.be/wp-content/uploads/2017/11/logo-long-white.png';
fileTransfer.download(url, this.file.dataDirectory + 'file.pdf').then((entry) => {
console.log('download complete: ' + entry.toURL());
}, (error) => {
// handle error
});
}
}
app.module.ts
providers: [
StatusBar,
AuthenticationService,
ScheduleService,
ToastService,
StorageService,
FacebookService,
GoogleService,
ImageService,
Facebook,
GooglePlus,
PushService,
File, <----------------
FileTransfer, <--------------
Push,
ScreenOrientation,
{
provide: HttpService,
useFactory: HttpFactory,
deps: [XHRBackend, RequestOptions]
},
{
provide: HttpNoAuthService,
useFactory: HttpFactory,
deps: [XHRBackend, RequestOptions]
},
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}

Ok I found out that the File class automatically imported in app.module.ts was not:
import { File } from '#ionic-native/file';
Instead it was some standard "lib.es6.d.ts" automatically imported.
So make sure you import the correct "File" class!

Related

Access to XMLHttpRequest at 'http://localhost:8082/kanchiwork/' from origin 'http://localhost:4200' has been blocked by CORS policy

When I tried to pass values from one server to other server am getting error as "Access to XMLHttpRequest at 'http://localhost:8082/kanchiwork/' from origin 'http://localhost:4200' has been blocked by CORS policy". My .ts file code
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class PeopleService {
constructor(private http:HttpClient) { }
fetchPeople(): Observable<Object>{
return this.http.get('http://localhost:8082/kanchiwork/');
//return this.http.get('assets/response.json');
}
}
where as if I placed the json file(response.json) in assets folder, it is working fine. I have followed the instruction given under the heading "Using corporate proxy" in the below URL, but still problem exists.
URL : https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md
For developing, You can define a proxy.dev.conf.json file to manage your request with Angular cli. eg: ng serve --open --proxy-config ./proxy.dev.conf.json
// config
[
{
"context": [
"/api/**"
],
"pathRewrite": {
"^/api": ""
},
"ws": false,
"target": "http://localhost:8082",
"secure": false,
"changeOrigin": true,
"logLevel": "debug"
}
]
// the service file
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class PeopleService {
constructor(private http:HttpClient) { }
fetchPeople(): Observable<Object>{
return this.http.get('/api/kanchiwork/');
//return this.http.get('assets/response.json');
}
}
Venkat, its not your fault because backend uses allow cross origin functionality on his side so that frontend not getting CORS error..
its error comes when you comes different url or port like cross domain.
Generally CORS error Means - CROSS ORIGIN RESOURCE SHARING it helps us to block request from Unwanted Sources, Which inturn increases security to our application, Your backend develepors should allow your url,
eg: if your backend developed in node js ask your team to add this code
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'example.com');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
//...
app.configure(function() {
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: 'cool beans' }));
app.use(express.methodOverride());
app.use(allowCrossDomain);
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
The proxy.conf path proposed by #xsong is correct, you just need to tweak it a little. First: don't hardcode the API path in the app itself (it's good practice anyway, regardless of proxy/no proxy/CORS/no CORS), put it in the environment.ts file. For developer build, you may define it simply as apiUrl: "/api".
Then, in your service(s), import the environment, send your requests at ${environment.apiUrl}/the-rest/of-the-path. And the third piece, you might need to rewrite path in the proxy.conf:
{
"context": [
"/api/**",
],
"target": "http://localhost:8082",
"secure": false,
"changeOrigin": true,
"logLevel": "debug",
"pathRewrite": {
"^/api": ""
}
}
It gets works by updating the files to the below ones.In proxy.config.json I updated the code as
{
"/api": {
"target": "http://localhost:8082",
"secure": false
},
"logLevel": "debug"
}
and in service file
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class PeopleService {
constructor(private http:HttpClient) { }
fetchPeople(): Observable<Object>{
return this.http.get('/api/kanchiwork/');
//return this.http.get('assets/response.json');
};
}
This code works for me and Thanks #xsong for your suggestions.

How to process http-Calls in Angular2/Ionic2

I'm currently trying to set up the Rest-API for my Ionic2 Application. As backend I'm using Crud-API which is working fine already. But I'm running into problems when calling the API from the APP.
I'm using the following class as a service to make the http call:
import {Http, Response} from '#angular/http';
import 'rxjs/add/operator/map';
export class NoteService {
static get parameters() {
return [[Http]];
}
constructor(private http:Http) {
}
searchNotes() {
var url = 'http://localhost/plotnote/api_crud.php/note/1';
var response = this.http.get(url).map(res => res.json());
return response;
}
}
Then I use the searchNotes-Method of this service to get the results and write them in the array notes:
import {Component} from '#angular/core';
import {NavController} from 'ionic-angular';
import {NoteService} from '../services/NoteService';
#Component({
selector: 'page-home',
templateUrl: 'home.html',
providers: [NoteService]
})
export class HomePage {
notes: Array<any>;
constructor(private navController: NavController, private noteService: NoteService) {
this.listNotes();
console.log("notes: " + this.notes);
}
listNotes() {
this.noteService.searchNotes().subscribe(
data => {
this.notes = data.results;
console.log('Data: ');
console.log(data);
},
err => {
console.log(err);
},
() => console.log('Note Search Complete')
);
}
}
Finally to display the notes I do the following:
<ion-content class="home" padding>
<ion-list>
<ion-card *ngFor="let note of notes">
<ion-card-content>
{{note.text}}
</ion-card-content>
</ion-card>
</ion-list>
</ion-content>
Sadly this doesn't work at all :(.
I tried to find the problem through the js-console and it looks like I'm getting the right data from the api, but there seems to be a problem with putting the data into the notes-Array.
Here is a screenshot of the console-output:
js-console output
I hope you guys can help me to find the problem and get this thing working :)

Angular 2 DI, use a custom Http

I have a service that uses Http:
import { Injectable } from '#angular/core';
import { Inject } from '#angular/core';
import { Http, Headers, Response } from '#angular/http';
#Injectable()
export class OrdersService {
constructor(#Inject(Http) private http:Http) {}
...
}
And a component that uses it
import { Component } from '#angular/core';
import { FormBuilder, Validators } from '#angular/common';
import { HTTP_PROVIDERS } from '#angular/http';
import { Router} from '#angular/router';
import { OrdersService } from '../services/orders.service'
#Component({
selector: 'login',
templateUrl: './login.component.html',
providers: [
HTTP_PROVIDERS, //{ provide: Http, useClass: Http }
AuthService, AuthStore,
OrdersService
]
})
export class LoginComponent {
constructor(private authService: AuthService, private ordersService: OrdersService){}
....
}
This works. I have some commented out text { provide: Http, useClass: Http }. I want to provide my own class here that extends Http, but still has all the same dependancies. The first step I'm taking here is to explicitly use Http.
As soon as I un-comment this text (and add an http import), everything breaks. I get the error "No provider for ConnectionBackend". It appears that HTTP_PROVIDERS has just stopped working as a provider.
How do I make this explicit use of Http work?
How do I use my own CustomHttp and use the providers in HTTP_PROVIDERS?
From Angular 2.1.1 and above syntax for provide option was changed after angular2 team introduce new modules concept. Below you will find correct syntax how to add your own custom provider for Http in your app.module.ts
export function httpFactory(backend: XHRBackend, defaultOptions: RequestOptions) {
return new CustomHttp(backend, defaultOptions);
}
...
providers: [
{provide: Http,
useFactory: httpFactory,
deps: [XHRBackend, RequestOptions]
}
]
You can also verify the angular2 documentation here: https://angular.io/docs/ts/latest/api/http/index/XHRBackend-class.html
If you want to implement you own CustomHttp class I will recommend you to read Thierry Templier article when step by step he is introducing how to do that.
Implementing CustomHttp for angular2 this is very helpful article which is describing how to extend to intercept request calls and add custom handling errors.
When using your own CustomHttp, you don't need to use HTTP_PROVIDERS, you need to do the following (in your app.module.ts if you are using RC5 or in your main.ts if you are using RC4):
providers: [
ConnectionBackend,
provide(
Http, {
useFactory: (
backend: XHRBackend,
defaultOptions: RequestOptions) =>
new CustomHttp(backend, defaultOptions),
deps: [XHRBackend, RequestOptions]
}),
]
I had the same problem, this fixed it for me.
Edit:
You don't need to import HTTP_PROVIDERS if you are using RC5 because you will import HttpModule, but I don't exactly remember if you need HTTP_PROVIDERS in RC4. You will probably need it.
If you don't want to change the implementations of XHRBackend and RequestOptions you can do it simplier like:
providers: [
{provide: Http, useClass: MyCustomHttp}
]

Injected service is undefined right in the constructor

For the note, I'm quite uninitiated to Angular (1 or 2 for that matter).
I'm trying to write a "super" layer of Http to avoid having to put the same headers everywhere.
import {Http, ConnectionBackend, RequestOptions, Response, Headers} from '#angular/http';
import {Observable} from 'rxjs';
import {LoadingService} from "../../services/loading.service";
export class HttpLoading extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions,
private _ls: LoadingService )
{
super(backend, defaultOptions);
}
getPostPutHeader() {
var authHeader = new Headers();
authHeader.append("Authorization", "Bearer "+ localStorage.getItem('token') );
authHeader.append('Content-Type', 'application/json');
return authHeader;
}
post(url: string, data:any):Observable<Response> {
this._ls.isLoading = true; // Exception here: this._ls is undefined
return super.post(url, data, { headers: this.getPostPutHeader() })
.map(res => {
this._ls.isLoading = false;
return res;
});
}
}
And a service to tell when a request is executing; it's injected in the above class HttpLoading.
import {Injectable} from '#angular/core';
#Injectable()
export class LoadingService {
isLoading: boolean = false;
}
I have a bunch of stuff in my bootstrap, including HttpLoading, LoadingService and ConnectionBackend (for this last one, I get an exception if it's not here).
bootstrap(AppComponent, [
ConnectionBackend,
HttpLoading,
APP_ROUTER_PROVIDERS,
HTTP_PROVIDERS,
LoadingService,
disableDeprecatedForms(),
provideForms()
])
The problem is that the first time I call HttpLoading's post method (in yet another service), I get an exception at this._ls.isLoading, because this._ls is undefined, and I can't figure why.
Please tell me if you need more information.
Edit
LoadingService is correctly injected in my AppComponent (main component).
//imports
//#Component
export class AppComponent {
requesting:boolean = false;
constructor(public authService: AuthService, private router: Router, private _ls: LoadingService) {
}
navigate(route:string) {
this._ls.isLoading = true;
this.router.navigate([route])
.then(() => this._ls.isLoading = false);
}
}
Potential solution
It seems that your public/private parameters must be placed first in the list. I'll let someone more skilled than me explain why, though...
export class HttpLoading extends Http {
constructor(private _ls: LoadingService, backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}
I would configure your HttpLoading class this way in the providers when bootstrapping your application:
bootstrap(AppComponent, [
(...)
HTTP_PROVIDERS,
{
provide:Http,
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, loadingService: LoadingService) => {
return new HttpLoading(backend, defaultOptions, loadingService);
},
deps: [XHRBackend, RequestOptions, LoadingService]
}
]);
The reason for this is that you want to use your own class for the Http provider. You need to change the class behind the Http provider by your HttpLoading class. Be careful to define it after HTTP_PROVIDERS.
To be able to inject the instance of XHRBackend to your class, you need to use useFactory...
Ok , I know that may seem trivial, but try to create a variable and initialize it in the constructor
To extend #Thierry Templier's answer. I am using Angular v4, and my experience is that you need to provide ALL the dependencies that your extending constructor needs, AND in the right order - I guess it's a legacy way of doing it, from angular 1.x.
My example:
// This is my extended class (relevant part only)
#Injectable()
export class HttpService extends Http {
constructor(
backend: ConnectionBackend,
defaultOptions: RequestOptions,
private router: Router,
private loaderService: LoaderService,
private modalService: ModalService,
private localStorageService: LocalStorageService
)
{
super(backend, defaultOptions)
}
// This is the provider factory defined in app.module.ts:
export function httpClientFactory(
backend: XHRBackend,
defaultOptions: RequestOptions,
router: Router,
loaderService: LoaderService,
modalService: ModalService,
localStorageService: LocalStorageService
) : Http
{
return new HttpService(
backend,
defaultOptions,
router,
loaderService,
modalService,
localStorageService
);
}
This is the configuration (just left the relevant part) in app.module.ts:
providers: [
ModalService
LocalStorageService,
LoaderService,
{
provide: HttpService,
useFactory: httpClientFactory,
deps: [XHRBackend, RequestOptions, Router, LoaderService, ModalService, LocalStorageService]
}
Note: notice the order of declaring the deps in the config compared to the factory constructor .. it is the same

Angular2 http does not include the X-XSRF-TOKEN [duplicate]

In Angular1 the problem can be solved by configuring $http-provider. Like:
app.config(function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
});
What is a good practice to do the same in Angular2?
In Angular2 to work with http requests we need to use class Http. Of course that's not a good practice to add CSRF-line to each call of post-function.
I guess in Angular2 I should create own class that inherits Angular2's Http class and redefine the post-function. Is it the right approach or is there a more elegant method?
Now that Angular 2 is released the following seems to be the correct way of doing this, by using CookieXSRFStrategy.
I've configured my application to have a core module but you can do the same in your main application module instead:
import { ModuleWithProviders, NgModule, Optional, SkipSelf } from '#angular/core';
import { CommonModule } from '#angular/common';
import { HttpModule, XSRFStrategy, CookieXSRFStrategy } from '#angular/http';
#NgModule({
imports: [
CommonModule,
HttpModule
],
declarations: [ ],
exports: [ ],
providers: [
{
provide: XSRFStrategy,
useValue: new CookieXSRFStrategy('csrftoken', 'X-CSRFToken')
}
]
})
export class CoreModule {
},
Solution for Angular2 is not as easy as for angular1.
You need:
Pick out csrftoken cookie value.
Add this value to request headers with name X-CSRFToken.
I offer this snippet:
import {Injectable, provide} from 'angular2/core';
import {BaseRequestOptions, RequestOptions} from 'angular2/http'
#Injectable()
export class ExRequestOptions extends BaseRequestOptions {
constructor() {
super();
this.headers.append('X-CSRFToken', this.getCookie('csrftoken'));
}
getCookie(name) {
let value = "; " + document.cookie;
let parts = value.split("; " + name + "=");
if (parts.length == 2)
return parts.pop().split(";").shift();
}
}
export var app = bootstrap(EnviromentComponent, [
HTTP_PROVIDERS,
provide(RequestOptions, {useClass: ExRequestOptions})
]);
Victor K's answer is perfectly valid however as of angular 2.0.0-rc.2, a preferred approach would be to use CookieXSRFStrategy as below,
bootstrap(AngularApp, [
HTTP_PROVIDERS,
provide(XSRFStrategy, {useValue: new CookieXSRFStrategy('csrftoken', 'X-CSRFToken')})
]);
For later versions of angular you cannot call functions in decorators. You have to use a factory provider:
export function xsrfFactory() {
return new CookieXSRFStrategy('_csrf', 'XSRF-TOKEN');
}
And then use the factory:
providers: [
{
provide: XSRFStrategy,
useFactory : xsrfFactory
}],
Otherwise the compiler will tell you off.
What I have also seen is that ng build --watch will not report this error until you kick it off again.
I struggled with this for a few days. The advice in this article is good, but as of August, 2017 is deprecated (https://github.com/angular/angular/pull/18906). The angular2 recommended approach is simple, but has a caveat.
The recommend approach is to use HttpClientXsrfModule and to configure it to recognize django's default csrf protection. According to the django docs, django will send the cookie csrftoken and expect the client to return the header X-CSRFToken. In angular2, add the following to your app.module.ts
import { HttpClientModule, HttpClientXsrfModule } from '#angular/common/http';
#NgModule({
imports: [
HttpClientModule,
HttpClientXsrfModule.withOptions({
cookieName: 'csrftoken',
headerName: 'X-CSRFToken',
})
], ...
The caveat is that angular2's XSRF Protection only applies to mutating requests:
By default, an interceptor sends this cookie [header] on all mutating requests
(POST, etc.) to relative URLs but not on GET/HEAD requests or on
requests with an absolute URL.
If you need to support an API that performs mutation on GET/HEAD, you will need to create your own custom interceptor. You can find an example and a discussion of the issue here.
Victor K had the solution, I'll just add this comment here as to what I did:
I created the component "ExRequestOptions" as Victor K said, but I also added a method "appendHeaders" to that component:
appendHeaders(headername: string, headervalue: string) {
this.headers.append(headername, headervalue);
}
Then I had this in my main.ts:
import {bootstrap} from 'angular2/platform/browser'
import {AppComponent} from './app.component'
import {HTTP_PROVIDERS, RequestOptions} from 'angular2/http';
import 'rxjs/Rx';
import {ExRequestOptions} from './transportBoxes/exRequestOptions';
import {provide} from 'angular2/core';
bootstrap(AppComponent,[ HTTP_PROVIDERS,
provide(RequestOptions, {useClass: ExRequestOptions})]);
I'm not sure the bootstrapping had any effect, so i also did this where
I would post data:
let options = new ExRequestOptions();
options.appendHeaders('Content-Type', 'application/json');
return this.http.post('.....URL', JSON.stringify(registration),
options)
Currently, I solve anything with custom headers using a wrapper service around the Http Service. You can add whatever header manually and inject additional services for storing/retrieving values. This strategy also works for JWTs, for example. Have a look at the code below, I hope it helps.
import {Injectable} from '#angular/core';
import {Http, Headers, RequestOptions} from '#angular/http';
#Injectable()
export class HttpService {
constructor(private http: Http) {
}
private get xsrfToken() {
// todo: some logic to retrieve the cookie here. we're in a service, so you can inject anything you'd like for this
return '';
}
get(url) {
return this.http.get(url, this.getRequestOptions())
.map(result => result.json())
.catch(error => error.json());
}
post(url, payload) {
return this.http.post(url, payload, this.getRequestOptions())
.map(result => result.json())
.catch(error => error.json());
}
private getRequestOptions() {
const headers = new Headers({'Content-Type': 'application/json', 'X-XSRF-TOKEN': this.xsrfToken});
return new RequestOptions({headers: headers});
}
}

Resources