i got a Problem. I want a global Service. I found this: Link.
It works but i want after initialized my component
an event what is called after my component is bootstrapped.
Anyone know this event?
Lyror
Update
yes i want to do that:
import {GlobalService} from './GlobalService';
import {Component, provide, Injector, ComponentRef} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS} from 'angular2/http';
import {appInjector} from './app.injector';
import {RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS,
LocationStrategy, HashLocationStrategy} from 'angular2/router';
import {AppComponent} from './app.component';
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
provide(LocationStrategy, { useClass: HashLocationStrategy }),
HTTP_PROVIDERS,
GlobalService
]).then((appRef: ComponentRef) => {
var injector = appInjector(appRef.injector);
var appComp: AppComponent = injector.get(AppComponent);
appComp.init();
});
But i get two Errors:
Unhandled Promise rejection: appComp.init is not a function ; Zone: ; Task: Promise.then ; Value: TypeError: appComp.init is not a function
Error: Uncaught (in promise): TypeError: appComp.init is not a function
The bootstrap function return a promise. The provided callback at this level is called when the component is bootstrapped:
bootstrap(AppComponent).then((compRef:ComponentRef) => {
// Do something after the component is bootstrapped
var comp = compRef.instance;
comp.init();
});
Related
I have created new Ionic 3 application using the latest version of Ionic CLI v4.9.0 using below
$ ionic start Ionic3Project blank --type ionic-angular
which create V4 Ionic project by default.
Then I followed steps for Native App Version Plugin here
Faced following console error when imported in app.module.ts file
Uncaught Error: Invalid provider for the NgModule 'AppModule' - only instances of Provider and Type are allowed, got: [StatusBar, ?[object Object]?, ...]
at syntaxError (compiler.js:486)
at compiler.js:15784
at Array.forEach (<anonymous>)
at CompileMetadataResolver._getProvidersMetadata (compiler.js:15752)
at CompileMetadataResolver.getNgModuleMetadata (compiler.js:15320)
at JitCompiler._loadModules (compiler.js:34413)
at JitCompiler._compileModuleAndComponents (compiler.js:34374)
at JitCompiler.compileModuleAsync (compiler.js:34268)
at CompilerImpl.compileModuleAsync (platform-browser-dynamic.js:239)
at PlatformRef.bootstrapModule (core.js:5578)
app.module.ts file
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { AppVersion } from '#ionic-native/app-version';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
#NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
AppVersion, <-- Error [[ts]
Type 'AppVersionOriginal' is not assignable to type 'Provider'.
Type 'AppVersionOriginal' is missing the following properties from type 'FactoryProvider': provide, useFactory [2322]]
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
UPDATE:Finally I found solution and explanation of this issue here :P
This issue is because of ionic new update(releasing ionic 4)
You have to import your plugins for ionic 3 like this:
import { PluginName} from '#ionic-native/pluginName/ngx';
More info here
This error is thrown because of the new update of ionic 4.
The above given solution would work perfectly.
But, this must be done throughout the project to avoid this error.
The other way could be to roll back to plugin's previous version.
I tried to use tensorflowjs in ionic. After converting existing model from python then import from ionic it works only when i runs on my local server (http://localhost:8100/ionic-lab)
However, when i build the project for android
tf.loadModel method not working, it fails to load model from local folder ( ie. assets/model )
I already checked this link Tensorflow.js with react-native
, but it doesn't help. I guess, lots of hybrid mobile app frameworks are pretty much the same line. Any advice and suggestions will be greatly appreciated.
import {Component} from '#angular/core';
import {IonicPage, AlertController} from 'ionic-angular';
import {HttpClient} from "#angular/common/http";
import * as tf from "#tensorflow/tfjs";
#IonicPage()
#Component({
selector: 'page-tfpretrainedversion',
templateUrl: 'tfpretrainedversion.html',
})
export class TfpretrainedversionPage {
kerasTraindedModel: tf.Model;
KERAS_MODEL_JSON = 'assets/model/model.json';
constructor(private httpClient: HttpClient,
private alertCtrl: AlertController) {
this.loadPretrainedModel();
}
loadPretrainedModel() {
tf.loadModel(this.KERAS_MODEL_JSON)
.then((result) => {
this.kerasTraindedModel = result;
})
.catch((error)=>{
let prompt = this.alertCtrl.create({
title: 'Error',
subTitle: error,
buttons: ['OK']
});
prompt.present();
});
}
}
Here is an error message
Failed to fetch
And here is a project structure
Project structure
TensorflowJs loads the models via fetch(). fetch() does not support loading local-files. https://fetch.spec.whatwg.org/
My Workaround:
Use a polyfill (https://github.com/github/fetch) and replace the fetch.
window.fetch = fetchPolyfill;
Now, it's possible to load local files (file:///) like:
const modelUrl = './model.json'
const model = await tf.loadGraphModel(modelUrl);
I am working with ionic v3.2.0 and as a part of requirement I have created another root component named as start.component.ts and start.modulue.ts. Which is a just copy of app.component.ts and app.modulue.ts.
I have implemented lazy loading in appModule.
main.ts
import { AppModule } from "./app.module";
platformBrowserDynamic().bootstrapModule(AppModule);
app.component.ts
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage: any = "LoginPage";
...
}
Everything is working fine and Login module is getting load.
No I changed to startModule
main.ts
import { StartModule } from "./start.module";
platformBrowserDynamic().bootstrapModule(StartModule);
start.component.ts
export class StartApp {
#ViewChild(Nav) nav: Nav;
rootPage: any = "LoginPage";
...
}
This is giving me error like :
main.js:1436 ERROR Error: Uncaught (in promise): invalid link: LoginPage
login.module.ts
import { NgModule } from '#angular/core';
import { IonicPageModule } from 'ionic-angular';
import { LoginPage } from './login';
#NgModule({
declarations: [
LoginPage
],
imports: [
IonicPageModule.forChild(LoginPage)
],
exports: [
LoginPage
]
})
export class LoginPageModule {}
login.ts
#IonicPage()
#Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
....
}
P.S. : If I remove LazyLoding, everything is working fine. And I have tried using latest ionic version 3.4.0, but same error.
Solution rename your file from start.module.ts back to app.module.ts.
because when ionic start compilation it start looking for file named app.module.ts when it didn't find it in app directory; then generate warning and error similar to this
The main app NgModule was not found at the following path:
C:\Users\muham\Documents\ionic-projects\todo\src\app\app.module.ts
Which means it is hard coded in ionic-cli for compilation process. So, application require file named app.module.ts in app to compile and build.
Hopefully this will resolve the problem
I am developing a front end which consumes JSON services provided by a server.
I happily use HTTP of Angular2 and I can catch errors via .catch() operator.
If I find a problem related to a specific service (e.g. the service is not defined by the server) the catch() operator receives a Response with status 404 and I can easily manage the situation.
On the other hand, if it is the server that is completely down, the catch() operator receives a Response with status code 200and no specific sign or text related to the cause of the problem (which is that the whole server is down).
On the console I see that angular (http.dev.js) writes a message net::ERR_CONNECTION_REFUSED but I do not know how to do something similar (i.e. understand what is happening and react appropriately) from within my code.
Any help would be appreciated.
If you would like to handle this event globally in your application I recommend using slightly modified Nicolas Henneaux's answer https://stackoverflow.com/a/37028266/1549135
Basically you can check for error.status === 0 which happens when the net::ERR_CONNECTION_REFUSED error occurs.
The complete module file:
import { Request, XHRBackend, BrowserXhr, ResponseOptions, XSRFStrategy, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
export class AuthenticationConnectionBackend extends XHRBackend {
constructor(_browserXhr: BrowserXhr, _baseResponseOptions: ResponseOptions, _xsrfStrategy: XSRFStrategy) {
super(_browserXhr, _baseResponseOptions, _xsrfStrategy);
}
createConnection(request: Request) {
let xhrConnection = super.createConnection(request);
xhrConnection.response = xhrConnection.response.catch((error: Response) => {
if (error.status === 0){
console.log("Server is down...")
}
...
return Observable.throw(error);
});
return xhrConnection;
}
}
Module file:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { HttpModule, XHRBackend } from '#angular/http';
import { AppComponent } from './app.component';
import { AuthenticationConnectionBackend } from './authenticated-connection.backend';
#NgModule({
bootstrap: [AppComponent],
declarations: [
AppComponent,
],
entryComponents: [AppComponent],
imports: [
BrowserModule,
CommonModule,
HttpModule,
],
providers: [
{ provide: XHRBackend, useClass: AuthenticationConnectionBackend },
],
})
export class AppModule {
}
I have the same problem while using angular2.0.0-beta.15
It seems like this is a bug. You get http status 200 and this is not correct:
https://github.com/angular/http/issues/54
Well i have faced something similar before. I was trying to make a logging Service and a Error handling which tells the user if error happened with some requests to the server or if the whole server is down.
I used HTTP Interceptor to catch the responses here is the code:
export class HttpErrorHandlingInterceptor implements HttpInterceptor {
constructor(private logService: LogService,
private layoutStateService: LayoutStateService){}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
if (req.url) {
return next.handle(req).pipe(
map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
return event;
}
}),catchError(err => {
if(!err.status){
this.layoutStateService.dispatchServerDown();
}else{
this.layoutStateService.dispatchAddServerError(err);
this.logService.logError(err);
}
throw err;
})
);
}
}
}
Now you can specify what should happen when Server is down according to your application.
Hope that helps.
index.js
Here is my entry point
import * as stylesheet from '../assets/styles/app.scss';
import jQuery from '../node_modules/jquery/dist/jquery';
import $ from '../node_modules/jquery/dist/jquery';
import {bootstrap} from './boot'
import {AppComponent} from './app.component'
bootstrap(AppComponent);
app.component.js
This works
(function (app) {
app.AppComponent = ng.core
.Component({
selector: 'my-app',
template: '<h1>My First Angular 2 App</h1>'
})
.Class({
constructor: function () {
}
});
})(window.app || (window.app = {}));
Question
I tried to use answer from How do I write angular2 without decorator syntax? without success.
How do I get rid of the IIFE and use ES6 syntax?
Untested!
import {Component} from 'angular2/core';
#Component({
selector: 'my-app',
template: `
<h1>
My First Angular 2 App
</h1>
`
})
export class AppComponent {
constructor () {
}
}
Perhaps you got a little confused by thinking you needed the app variable?
Just to be clear you don't need to reference app, you just need to import AppComponent (as you already have)
If you are using Babel and use the following plugins: 'angular2-annotations', 'transform-decorators-legacy', 'transform-class-properties', 'transform-flow-strip-types' there is no need to convert the syntax.
You can check it also in a working example.