Beyond the Tour of Heroes - angularjs

I am new to Angular, background is server side Java, .Net...
So, I completed the Tour of Heroes and I have created simple hard coded multi-page application. Now I need to go the next step and call the server to retrieve data via a rest/JSON call. Based on the AngularJS example:
https://angular.io/docs/ts/latest/guide/server-communication.html
and a few other blogs such as:
http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html
I have a pretty good understanding of how it is supposed to work. However, I see two errors now:
In the browser: Cannot resolve all parameters for 'AuthService'(?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'AuthService' is decorated with Injectable.
and in NPM:
app/auth.service.ts(9,19): error TS2304: Cannot find name 'Http'.
I have no clue how to chase the dependencies down. packages.json? typings.json, tsconfig.json... Or how they all work; and I cannot find any documentation; any suggestions?
auth.service:
import {Injectable} from 'angular2/core';
import {HTTP_PROVIDERS} from 'angular2/http';
#Injectable()
export class AuthService {
items:Array<any>;
constructor(http:Http) {
}
}
main.ts
import {bootstrap} from 'angular2/platform/browser'
import {AppComponent} from './app.component'
import {HTTP_PROVIDERS} from 'angular2/http';
import { AuthService } from './auth.service';
bootstrap(AppComponent, [HTTP_PROVIDERS, AuthService]);
I have not consumed the Auth.Service in an component yet.
Tim

I think the problem is you are not pulling in Http, just HTTP_PROVIDERS, in your auth.service try this
import {Http} from 'angular2/http'

Related

How to import src module to public folder in react?

As I'm using Firebase Cloud Messaging in my React, it requires me to put the firebase-messaging-sw.js in my public folder.
In there, it is defining the function for the onBackgroundMessage, which I want to have an access to my module, and update some of my components in my src.
import { toast } from "react-toastify"; // or import my other modules
messaging.onBackgroundMessage(function(payload) {
console.log('Received background message ', payload);
//toast or do some updating my modules
toast(`Message received : ${payload}`) // here comes the error
});
But I got an error of
Uncaught SyntaxError: Cannot use import statement outside a module (at
firebase-messaging-sw.js:3:1)
How can I import my src module to the public folder?
How should I properly use the onBackgroundMessage in React?
is it normal to import module from src to the public folder?
Use importScripts to import scripts into the worker's scope like firebase-messaging itself.
importScripts('https://www.gstatic.com/firebasejs/9.2.0/firebase-messaging.js');

Dynamic file import in Angular Project

I'm building an hybrid angular app. The AngularJs Code has three different file for constants based on environment, created in this way
angular.module(...).constants(...).
I have a file called index.ts where i import the files of my project.
index.ts
import "./js/constants";
import "./js/constants_svil";
import "./js/constants_stage";
import "./js/constants_dev";
import "./js/angular-multi-select";
import "./js/angular-indexed-db";
import "./js/calendar";
import "./js/abmoment.min";
import "./js/acmoment-timezone-with-data";
import "./js/amoment-timezone-utils";
import "./js/fullcalendar";
import "./js/gcal";
import "./js/lang-all";
Is there a way to dynamically load this constants file based on environment? I saw there is a dynamic import used to load modules implemented in Typescript 2.4. Could it work? I need this file only for side effects, they don't have an export statement inside.
Edit: Now i'm using typescript 3.9
you can define different files for different build configurations in the angular.json:
example:
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
...
see: https://angular.io/guide/build

TypeError: __webpack_require__.i(...) is not a function

I am getting a webpack TypeError when I am trying to simplify an import. The following code works without any issues. Here I am importing a React Higher-Order-Component (HOC) called smartForm from core/components/form/index.js.
core/components/form/index.js (does a named export of smartForm)
export smartForm from './smart-form';
login-form.jsx (imports and uses smartForm)
import { smartForm } from 'core/components/form';
class LoginForm extends React.Component {
...
}
export default smartForm(LoginForm);
However, I want to simplify the import to just import { smartForm } from 'core'. So I re-exported smart-form in core/index.js and imported it from core. See the code below:
core/index.js (does a named export of smartForm)
export { smartForm } from './components/form';
// export smartForm from './components/form'; <--- Also tried this
login-form.jsx (imports and uses smartForm)
import { smartForm } from 'core';
class LoginForm extends React.Component {
...
}
export default smartForm(LoginForm); // <--- Runtime exception here
This code compiles without any issues, but I am getting the following runtime exception at the line export default smartForm(LoginForm);:
login-form.jsx:83 Uncaught TypeError: webpack_require.i(...) is not a function(…)
What am I missing?
P.S. Here are the Bable and plugin versions that I am using:
"babel-core": "^6.18.2",
"babel-preset-es2015-webpack": "^6.4.3",
"babel-preset-react": "^6.16.0",
"babel-preset-stage-1": "^6.16.0",
tl;dr
For the questioner: Add this to your webpack.config.js:
resolve: {
alias: {
core: path.join(__dirname, 'core'),
},
},
For the general audience: Make sure the thing you try to import is indeed exists in that package.
Explanation
Questioner's problem: importing own code like npm modules
You try to import your module's exports in the same fashion how you import something from an npm package from the node_modules folder: import { something } from 'packagename';. The problem with this is that doesn't work out of the box. The Node.js docs give the answer on why:
Without a leading '/', './', or '../' to indicate a file, the module must either be a core module or is loaded from a node_modules folder.
So you either has to do what Waldo Jeffers and Spain Train suggested and write import { smartForm } from './core', or you can configure webpack so it can resolve your import path via its aliases which are created to solve this exact problem.
Debugging the error message in general
This error can arise if you try to import something from an existing npm package (in node_modules) but the imported thing doesn't exist in the exports. In this case, make sure there were no typos and that the given thing you try to import is indeed in that package. Nowadays it is trendy to break libraries into multiple npm packages, you might be trying to import from a wrong package.
So if you get something like this:
TypeError: __webpack_require__.i(...) is not a function
at /home/user/code/test/index.js:165080:81
at Layer.handle [as handle_request] (/home/user/code/test/index.js:49645:5)
To get more information on what import you should check, just open the output file generated by webpack and go to the line marked by the topmost line in the error stack (165080 in this case). You should see something like: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_9_react_router_dom__["match"]). This tells us that there is no match export (or there is but it isn't a function) in react-router-dom, so we need to check our stuff around that import.
Since core is a folder of your app and not an npm module, Webpack can not understand which file you want to load. You must use a correct path pointing to a file. You have to replace import { smartForm } from 'core'; by import { smartForm } from './core/index.js
This error will occur by many reasons. Once I encountered this error when I add js in file-loader then when I removed it start to work correctly.
{
test: /\.(ttf|eot|svg|gif|jpg|png|js)(\?[\s\S]+)?$/,
use: 'file-loader'
},
When I remove |js it works
{
test: /\.(ttf|eot|svg|gif|jpg|png)(\?[\s\S]+)?$/,
use: 'file-loader'
},
Just remove these 2 line from config
const context = resolve.alias.context('./', true, /\.spec\.ts$/); context.keys().map(context);

Use javascript libraries installed by npm

I'm sorry, but I'm very lost. Actually I have this:
import * as angular from 'angular';
import 'ts-angular-jsonapi';
And dont return any errors. But, when I do this
import * as angular from 'angular';
import * as jsonapi from 'ts-angular-jsonapi';
I get this error:
ERROR in ./src/index.ts
(14,23): error TS2307: Cannot find module 'ts-angular-jsonapi'.
What changes need I do on ts-angular-jsonapi library for fix this errors.
More info: I need do this becouse I need make something like this:
class myresource extend jsonapi.resource {
}
I found the solution. When you write a .TS file, you can not import any .JS file. You need use require(). In the code:
// some_file.ts
import * as angular from 'angular';
var jsonapi = require('ts-angular-jsonapi'); // .js library
But if you are searching the best and correct solution for typescript node module, I build a simple example on github. With this example, you can do something like this:
import * as animal_module from 'animal_module';
class Snake extends animal_module.Animal {
constructor(name: string) { super(name); }
}
let sam = new Snake('Sammy the Python');
why don't you try
import angular from 'angular'; import jsonapi from 'ts-angular-jsonapi';

How to fix angular 2 error Cannot read property 'getOptional'?

I am getting my head around angular 2 and trying to define a service called searchservice and inject this in the bootstap part:
import {SearchService} from 'src/service';
This is what the service looks like:
import {Injectable} from 'angular2/core';
import {URLSearchParams, Jsonp} from 'angular2/http';
#Injectable()
export class SearchService {
constructor(private http: Http) {}
search (name: string) {
http.get('https://api.spotify.com/v1/search?q='+name.value+'&type=artist')
.map(response=>response.json());
}
}
However how can I fix this error that comes up when running the app?:
VM337 angular2-polyfills.js:138 Error: Cannot read property 'getOptional' of undefined
Error loading http://run.plnkr.co/fGkpQYXMc0eGUy6e/src/boot.ts
at _runAppInitializers (https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.0/angular2.dev.js:14832:25)
at PlatformRef_._initApp (https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.0/angular2.dev.js:14813:7)
at PlatformRef_.application (https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.0/angular2.dev.js:14768:22)
at Object.bootstrap (https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.0/angular2.dev.js:25054:64)
at execute (http://run.plnkr.co/fGkpQYXMc0eGUy6e/src/boot.ts!transpiled:60:23)
at u (https://rawgit.com/systemjs/systemjs/0.19.6/dist/system.js:5:97)
at Object.execute (https://rawgit.com/systemjs/systemjs/0.19.6/dist/system.js:5:3188)
at y (https://rawgit.com/systemjs/systemjs/0.19.6/dist/system.js:4:9948)
at w (https://rawgit.com/systemjs/systemjs/0.19.6/dist/system.js:4:10327)
plunkr ref:http://plnkr.co/edit/F6TSGfyRnR5jvbpiv2QJ?p=preview
The important part of the error is the line above the one you listed, which says:
Cannot resolve all parameters for SearchService(?). Make sure they all have valid type or annotations.
Your search service is trying to define a variable of type Http but you didn't import Http into the service.
change the import line to import {URLSearchParams, Jsonp, Http} from 'angular2/http';.

Resources