Content Source:
- blog.angular.io
Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone while being compatible with the newest features of React.
While working with react you might have noticed that are different ways to manage the global state management in React. Let’s take look at the options that we have:
Redux is a predictable state container for JavaScript apps.
It is used by a lot of web apps these days, it allows us to have a global state, register components to it and they will re-render by themselves every time a value they registered to will change.
Context API is another approach that devs take for better management of state within the application.
Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.
Now that we are already using to above two famous ways of adding global state to our application here comes something new i.e Recoil.
Recoil lets you create a data-flow graph that flows from atoms (shared state) through selectors (pure functions) and down into your React components.
React
local component state. If the same atom is used from multiple components, all those components share their state.Let’s try to understand this with a Demo example.
Consider we want to store user data upon login into our application and share between two components,
Let first define an atom which stores the logged-in user Data
pic courtesy: blog.bitsrc.io
In the above example, we have stored the object which has a name in it. It is stored inside our loggedInUserData
atom.
Now consider we need to show this name in our useRecoilState
.
pic courtesy: blog.bitsrc.io
And our component looks something like this, which display the data from the same atom which is used in the header component again with help of useRecoilState
pic courtesy: blog.bitsrc.io
The syntax might look quite similar to useState which we are already used to in react
hooks.
As in the above example since the same state is shared between the
This is one of the important hooks in the Recoil API. This hook will just subscribe to the component to the given Recoil state, it is used to return the value of the given Recoil state.
For more information and to develop web application using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using React JS, please visit our technology page.
Content Source:
This is a minor release of the framework and the CLI that is a drop-in replacement for 9.0 containing new features and bug fixes.
Today, the Angular libraries you use are made compatible with the Ivy compiler via our ngcc
tool. Previously, the ngcc
compilation pass covered all of your Angular library dependencies sequentially. In 9.1, we’ve improved the speed of ngcc
, and allowed it to compile multiple packages concurrently.
These changes will help make builds faster and improve reliability for teams with monorepository-style workspace layouts.
We’ve added support for TypeScript 3.8, in addition to our existing support for 3.6 and 3.7.
This release adds many great features to the TypeScript language, including:
Angular components are displayed inline
by default, as that’s the default for most DOM elements. It’s very common for developers to want components to use the display: block
style. When you create a new component, you can now set this up automatically.
ng generate component my-component --displayBlock
To turn this on by default, set the schematics.@schematics/angular:component.displayBlock
key in your angular.json
to true, or use:
ng config schematics.@schematics/angular:component.displayBlock true
When running end-to-end tests, we now pass the grep
and invertGrep
options to the Protractor builder, allowing you to more easily choose the test you want to run.
ng e2e --grep searchTerm
If you use VSCode and our Language Service Extension, starting today our extension will allow your IDE to syntax highlight expressions in your templates, using a TypeScript-like formatter. It will also add syntax highlighting to your inline HTML templates in your components.
pic courtesy : blog.angular.io
Note: We worked with the authors of angular2-inline and vscode-angular-html on these features. If you use either of these extensions, you’ll need to disable them for this functionality to work.
If you build an application with Internationalization, you may be building a single app that supports Right to Left locales. You can now query for the current direction at runtime.
import { getLocaleDirection, registerLocaleData } from '@angular/common'; import { LOCALE_ID } from '@angular/core'; import localeAr from '@angular/common/locales/ar'; ... constructor(@Inject(LOCALE_ID) locale) { getLocaleDirection(locale); // 'rtl' or 'ltr' based on the current locale registerLocaleData(localeAr, 'ar-ae'); getLocaleDirection('ar-ae'); // 'rtl' // Now use the current direction in your app. // You can conditionally specify an image URL for example }
Newly created projects will now use TSLint 6.1 by default. If you want to migrate to the latest version, make sure you are on version 9.1 first, then you can opt-in via:
ng update @angular/cli --migrate-only tslint-version-6
We do not run this migration automatically because there are some minor breaking changes in TSLint 6.1.
This release includes lots of other bug fixes, performance improvements, and minor features. Version 9.1 also improves the compatibility story with our new compiler and runtime. If you previously attempted to enable Ivy with version 9.0 and ran into issues, try again with version 9.1.
Update to the latest version of Angular to get access to these new capabilities and bug fixes.
ng update @angular/cli @angular/core
For more information and to develop web application using Angular, Hire Angular Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop any custom web apps using Angular, please visit our technology page.
Content Source:
Babel is a JavaScript compiler that includes the ability to compile JSX into regular JavaScript.
Array.from
and built-ins like Promise
are only available in ES6+, but they can be used in older environments if a Babel polyfill is.@babel/register is often used in Node.js. It makes the babel run dynamically when the require
code is executed. Since it’s not popular way to run babel in React, we are not going to deal with @babel/register way.
Let’s Create sample project.
— Create a directory and package.json
mkdir test-babel-how cd test-babel-how npm init -y
— Install the necessary packages
npm i @babel/core @babel/cli @babel/plugin-transform-arrow-functions @babel/plugin-transform-template-literals @babel/preset-react
— Create a sample code
src
folder and create code.js
in the src
folder.test-babel-how | -- node_modules -- src | -- code.js -- package-lock.json -- package.json
const element = <div>babel test</div>; // 1 const text = `element type is ${element.type}`; // 2 const add = (a,b)> a + b; // 3
We are going to:
— run the following command in the terminal
npx babel src/code.js // 1 --presets=@babel/preset-react // 2 --plugins=@babel/plugin-transform-template-literals, // 3 @babel/plugin-transform-arrow-functions
src/code.js
.@babel/preset-react
.@babel/plugin-transform-template-literals
& @babel/plugin-transform-arrow-functions
.— Following output in the terminal
const element = /*#__PURE__*/React.createElement("div", null, "babel test" ); // 1 const text = "element type is ".concat(element.type); // 2 const add = (a, b) > a + b; // 3
concat
method.— install packages to use webpack
npm i webpack webpack-cli babel-loader
— create a babel.config.js
file
const presets = ['@babel/preset-react']; const plugins = [ '@babel/plugin-transform-template-literals', '@babel/plugin-transform-arrow-functions' ]; module.exports = { presets, plugins };
babel.config.js
to specify presets & plugins.— create a webpackge.config.js
file
const path = require('path'); module.exports = { entry: './src/code.js', // 1 output: { // 2 path: path.resolve(__dirname, 'dist'), filename: 'code.bundle.js', }, module: { // 3 rules: [{ test: /\.js$/, use: 'babel-loader'}], }, optimization: { minimizer: []} , // 4 }
dist/code.bundle.js
file.babel-loader
to handle JavaScript files.babel.config.js
file.— run webpack
npx webpack
— dist/code.bundle.js
is created with a following output:
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; // ... // ... /* 0 */ /***/ (function(module, exports) { const element = /*#__PURE__*/React.createElement("div", null, "babel test"); // 1 const text = "element type is ".concat(element.type); // 2 const add = (a, b) > a + b; // 3 /***/ }) /******/ ]);
// ...
part is webpack’s run time code.— create runBabel.js
file
const babel = require('@babel/core'); // 1 const fs = require('fs'); const filename = './src/code.js'; const source = fs.readFileSync(filename, 'utf8'); // 2 const presets = ['@babel/preset-react']; // 3 const plugins = [ '@babel/plugin-transform-template-literals', '@babel/plugin-transform-arrow-functions', ]; const { code } = babel.transformSync(source, { // 4 filename, presets, plugins, configFile: false, // 5 }); console.log(code); // 6
code.js
to compiletransformSync
function— run file
node runBabel.js
const element = /*#__PURE__*/React.createElement("div", null, "babel test" ); // 1 const text = "element type is ".concat(element.type); // 2 const add = (a, b) > a + b; // 3
For more information and to develop web application using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop any custom web apps using React JS, please visit our technology page.
Content Source:
React 16.13.0 contains bugfixes and new deprecation warnings to help prepare for a future major release.
A React component should not cause side effects in other components during rendering.
It is supported to call setState
during render, but only for the same component. If you call setState
during a render on a different component, you will now see a warning:
Warning: Cannot update a component from inside the function body of a different component.
This warning will help you find application bugs caused by unintentional state changes.
In the rare case that you intentionally want to change the state of another component as a result of rendering, you can wrap the setState
call into useEffect
.
When dynamically applying a style
that contains longhand and shorthand versions of CSS properties, particular combinations of updates can cause inconsistent styling. For example:
<div style={toggle ? { background: 'blue', backgroundColor: 'red' } : { backgroundColor: 'red' } }> ... </div>
You might expect this <div>
to always have a red background, no matter the value of toggle
. However, on alternating the value of toggle
between true and false, the background color start as red
, then alternates between transparent
and blue
, as you can see in this demo.
React now detects conflicting style rules and logs a warning. To fix the issue, don’t mix shorthand and longhand versions of the same CSS property in the style
prop.
String Refs is an old legacy API which is discouraged and is going to be deprecated in the future
<Button ref="myRef" />
For example, it will fire if you use String Refs together with the Render Prop pattern:
class ClassWithRenderProp extends React.Component { componentDidMount() { doSomething(this.refs.myRef); } render() { return this.props.children(); } } class ClassParent extends React.Component { render() { return ( <ClassWithRenderProp> {() => <Button ref="myRef" />} </ClassWithRenderProp> ); } }
Code like this often indicates bugs. (You might expect the ref to be available on ClassParent
, but instead it gets placed on ClassWithRenderProp)
You most likely don’t have code like this. If you do and it is intentional, convert it to React.createRef()
instead:
class ClassWithRenderProp extends React.Component { myRef = React.createRef(); componentDidMount() { doSomething(this.myRef.current); } render() { return this.props.children(this.myRef); } } class ClassParent extends React.Component { render() { return ( <ClassWithRenderProp> {myRef => <Button ref={myRef} />} </ClassWithRenderProp> ); } }
React.createFactory
is a legacy helper for creating React elements. This release adds a deprecation warning to the method. It will be removed in a future major version.
Replace usages of React.createFactory
with regular JSX. Alternately, you can copy and paste this one-line helper or publish it as a library:
let createFactory = type => React.createElement.bind(null, type);
When React 16 was released, createPortal
became an officially supported API.
However, we kept unstable_createPortal
as a supported alias to keep the few libraries that adopted it working. We are now deprecating the unstable alias. Use createPortal
directly instead of unstable_createPortal
. It has exactly the same signature.
React adds component stacks to its development warnings, enabling developers to isolate bugs and debug their programs. This release adds component stacks to a number of development warnings that didn’t previously have them. As an example, consider this hydration warning from the previous versions:
pic courtesy: reactjs.org
While it’s pointing out an error with the code, it’s not clear where the error exists, and what to do next. This release adds a component stack to this warning, which makes it look like this:
pic courtesy: reactjs.org
This makes it clear where the problem is, and lets you locate and fix the bug faster.
This release contains a few other notable improvements:
shouldComponentUpdate
. This shouldn’t affect most code, unless you have side effects in shouldComponentUpdate
. To fix this, move the code with side effects into componentDidUpdate
.onMouseEnter
now doesn’t trigger on disabled <button>
elements.version
export since we published v16. This release adds it back. We don’t recommend using it in your application logic, but it’s useful when debugging issues with mismatching / multiple versions of ReactDOM on the same page.React v16.13.0 is available on the npm registry.
To install React 16 with Yarn, run:
yarn add react@^16.13.0 react-dom@^16.13.0
To install React 16 with npm, run:
npm install --save react@^16.13.0 react-dom@^16.13.0
We also provide UMD builds of React via a CDN:
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
For more Information and to build a website using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“. To develop your custom website using React JS, please visit our technology page.
Content Source:
The 9.0.0 release of Angular is here! This is a major release that spans the entire platform, including the framework, Angular Material, and the CLI.
Version 9 moves all applications to use the Ivy compiler and runtime by default. In addition to hundreds of bug fixes, the Ivy compiler and runtime offers numerous advantages:
Here’s a breakdown of some of the more notable improvements.
The Ivy compiler has been designed to remove parts of Angular that aren’t being used via tree-shaking and to generate less code for each Angular component.
With these improvements, small apps and large apps can see the most dramatic size savings.
Small apps could see around a 30% decrease in bundle size, large apps will see a 25–40% decrease, and medium apps decrease minimally. – pic courtesy: blog.angular.io
We have also revamped the implementation of TestBed in Ivy to make it more efficient.
Previously, TestBed would recompile all components between the running of each test, regardless of whether there were any changes made to components (for example, through overrides).
In Ivy, TestBed doesn’t recompile components between tests unless a component has been manually overridden, which allows it to avoid recompilation between the grand majority of tests.
With this change, the framework’s core acceptance tests are about 40% faster. We would expect users to see their own application test speeds to be around 40–50% faster.
Ivy provides you with more tools to debug your applications. When running an application in Dev Mode with the Ivy runtime, we now offer the new ng object for debugging.
pic courtesy: blog.angular.io
Ivy also improves the stack trace for debugging issues such as the ExpressionChangedAfterItHasBeenCheckedError. Previously the stack trace could be unhelpful:
pic courtesy: blog.angular.io
With Ivy, you see a more useful stack trace that allows you to jump directly to the template instruction with the expression that has changed.
pic courtesy: blog.angular.io
For example, if you click on AppComponent_Template in the stack trace above, you can see the specific line in the generated code where the error is being thrown:
If you’re so inclined, you can also step into any of these framework instructions to walk through how the framework creates or updates your components.
The Ivy compiler and runtime provides improvements for handling styles. Previously, if an application contained competing definitions for a style, those styles would destructively replace each other. With Ivy, the styles are merged in a predictable way.
Consider the following template and component snippets:
<my-component style="color:red;" [style.color]="myColor" [style]="{color: myOtherColor}" myDirective></div>
@Component({ host: { style: "color:blue" },... }) ... @Directive({ host: { style: "color:black", "[style.color]": "property" },... }) ...
Previously, whichever binding was evaluated last would win, and this could depend on the timing of changes to these expressions. If myColor and myOtherColor both were undefined, the static ‘red’ style would be ignored.
With version 9, you can manage your styles through a clear, consistent order of precedence that isn’t dependent on timing. The most specific styles always have the highest precedence. For example, a binding to [style.color] overrides a conflicting binding to [style].
However, for backwards compatibility reasons, we have left [ngStyle] and [ngClass] bindings behavior the same as before. When their binding values are updated, the new values will override any competing bindings.
You can read more about styling precedence rules in the Template Syntax guide in the documentation.
As a side effect of the styling refactoring, you can now also bind to CSS custom properties (also known as CSS variables).
<div [style.--main-border-color]=" '#CCC' "> <p style="border: 1px solid var(--main-border-color)">hi</p> </div>
Thanks to Ivy’s new architecture, we’ve made significant improvements to the compiler’s performance.
We measure our compiler’s performance in terms of the overhead on top of a plain TypeScript compilation of an application. For our documentation app (angular.io), this overhead decreased from 0.8x to 0.5x with Ivy, an improvement of nearly 40%.
These improvements mean that AOT builds can be noticeably faster. Thanks to this speedup, for the first time ever we’re using AOT even for dev-mode builds. This means that `ng serve` now benefits from the same compile-time checking as production builds, significantly improving the developer experience for Angular.
Thanks to the changes in the compiler and runtime, we also no longer require entryComponents. These components will be discovered and compiled automatically by their usage.
For more information and to develop your web apps using Angular, Hire Angular Developer from us as we provide you high-quality solution by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop the custom web app using Angular, please visit our technology page.
Content Source:
JavaScript is the standard technology for implementing a seamless interaction between a user and the web page. Almost all modern browsers support it. It is the main technology behind driving the modern UX and/or server-side frameworks such as Angular, Node.JS and ReactJS. Here are top 5 best practices to write more robust JavaScript.
If you don’t know what a factory function is, it’s simply a function (that isn’t a class or constructor) that returns an object. This simple concept allows us to take advantage of JavaScript and its features to create powerful robust applications.
It’s important to know that they’re no longer factory functions when they’re called with the new
keyword.
Factory functions can be used to easily produce instances of objects without having anything to do with classes or the new
keyword.
What it essentially means is that they ultimately become treated as just functions, which means they can be used to compose objects, functions, and even promises. This means you can mix and match factory functions together to create an enhanced factory function, then continue composing with other functions or objects to create even further enhanced ones. The possibilities are endless.
When we take that into consideration and combine it with good code practices, it really begins to shine.
Here is a simple example of a factory function:
function createFrog(name) { const children = [] return { addChild(frog) { children.push(frog) }, } } const mikeTheFrog = createFrog('mike')
When you’ve used factory functions enough, you begin to realize that compared to its class constructor counterpart, it promotes stronger reusability. This results in less code, an easier time refactoring since factory functions ultimately return arbitrary objects, and an easier time managing one code to another.
If you’re new to JavaScript, this section might be a little new to you as it was for me for the first two years of my experience with JavaScript.
(Keep in mind that this does not apply to classes because classes already attach methods onto their prototypes.)
Here’s an example of a constructor:
function Frog(name, gender) { this.name = name this.gender = gender } Frog.prototype.leap = function(feet) { console.log(`Leaping ${feet}ft into the air`) }
Why do this instead of directly attaching the leap method, like in the example below?
function Frog(name, gender) { this.name = name this.gender = gender this.leap = function(feet) { console.log(`Leaping ${feet}ft into the air`) } }
When we attach methods directly on the prototype, they get shared among all instances created by the constructor.
In other words, using the last example, if we created three separate Frogs (from this.leap = function() {…}), then we end up creating three separate copies. This is a problem because the leap method will always stay the same and doesn’t need to have its own copy to its instance.
Ultimately, this results in lower performance, when it could have been avoided. The this.name and this.gender properties need to be defined on the instance because in real life, frogs probably have their own names and gender so it makes sense to have them created on the instance level.
Here’s an example on GitHub of this approach used by the popular request package.
This practice works so well that it’s in extensive use today. If you’re a React developer, you’ve probably already been seeing this every day, especially when you’ve been working with Redux.
Using similar approaches also makes it extremely easy for you in your development flow since it even documents itself extremely well:
function createSpecies(type, name, gender) { if (type === 'frog') { return createFrog(name, gender) } else if (type === 'human') { return createHuman(name, gender) } else if (type == undefined) { throw new Error('Cannot create a species with an unknown type') } } const myNewFrog = createSpecies('frog', 'sally', 'female')
TypeScript has become widely adopted in the JavaScript community due to its ability to provide a strong defense for type safety as well as its ability to help us catch bugs before they even occur.
Using TypeScript will enable your compiler to detect and show warnings about any potential errors in code before the code even runs.
But that’s not even close to a complete list of reasons why adopting TypeScript is good for any situation. One of the best things about TypeScript is that it allows you to use new features in JavaScript before they’re supported by major browsers since they get compiled down to earlier versions of JavaScript, ultimately being able to run in old browsers.
try/catch
when using JSON.parse
or JSON.stringify
In JavaScript, when we pass JSON as input to the JSON.parse
method, it expects a properly formatted JSON as the first argument. If it’s formatted incorrectly, it will throw a JSON parse error.
The danger coming from JSON parse errors is that receiving invalid JSON crashes your app. We’ve recently been in a situation at work where one of our web projects was failing because another internal package did not wrap a JSON.parse
in a try/catch
. This ended up making a web page fail, and there was no way to get past this error unless the internal package fixed it. This happened because the JavaScript runtime was broken.
SyntaxError: Unexpected token } in JSON at position 107
You shouldn’t always expect valid JSON input as it can receive weird characters like the >character, which is not uncommon today.
For more information and to design a website using front-end technology, Hire Front-End Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“. To develop your custom website using JS, please visit our technology page.
Content Source:
First off, let’s go over what Capacitor is and how it relates to other cross platform projects out there.
At a glance, Capacitor follows many of the same ideas as Apache Cordova.
pic courtesy: blog.angular.io
There is a Web layer that renders the app and a native layer that listens for calls to Native APIs. Within those layers are many technical decisions that make the overall developer and user experience much smoother.
npm
and modern JS tooling to simplify adding core plugins and creating new ones.These principles bring the best of web development and native development with little to no friction for developers.
Capacitor itself is made up of 2 packages, the core functionality (@capacitor/core)
and the CLI (@capacitor/cli)
. To add Capacitor to your project, let’s start with a simple Angular App from the Angular CLI.
ng new capApp --routing --style css cd capApp
With the app created, let’s add Capacitor to our project.
ng add @capacitor/angular
With this, developers can add Capacitor to their project with ease.
pic courtesy: blog.angular.io
When the schematic is done running, developers should build our app, and run npx cap add <ios,android>
or yarn cap add <ios, android>
and our Xcode or Android Studio projects will be created!
ng run capApp:build npx cap add ios
First, it adds Capacitor dependencies to the package.json
: Core and CLI.
This will just do a quick npm (or yarn) install then make sure we have the Core and CLI packages for Capacitor.
To make sure that the Capacitor project understands your Angular project, the schematic infers a lot of data based on your angular.json. It will read your app’s name and use that when creating the iOS and Android projects, as well as read the build folder so it knows where to copy your web code when preparing the native projects. This means that your Capacitor project will feel like a natural extension of your Angular project.
Once added, we do a build of our app, and deploy to either iOS, Android, web, or Electron. For building to iOS or Android, you’ll need to have the native SDKs and tools installed.
For more Information and to build the website using Angular, Hire Angular Developer from us as we give you high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop the custom web app using Angular, please visit our technology page.
Source:
An interface is a programming feature that helps to define the expected structure of an object allowing that to serve as a contract of sorts for the class where it is implemented.
That helps explain the concept but how does this actually translate into working with real world code?
Let’s say for example we have the following method:
public requestSpecificArea(lat : number, lng : number) : Observable { return this.http.get(this._api + `locate-neighbourhood?q=${lat},${lng}`); }
As you can gather from the code we’re using Angular’s HttpClient class to query a remote API which returns data as an observable that we can subsequently subscribe to.
The data that is returned will be structured as follows:
{ "description": [ { "id":1, "region":"somewhere", "summary":"something" }, { "id":2, "region":"somewhere else", "summary":"something else" } ] }
Should be fairly straightforward and any expected data will be returned right?
Not necessarily.
If Angular doesn’t ‘understand’ the returned data then the HttpClient object will return back an error like the following:
Property 'description' does not exist on type Object
Pretty frustrating right?
This is where interfaces come to the rescue.
In the previous example Angular’s HttpClient class didn’t understand the shape of the returned object hence the error that was published to the console.
Using interfaces we can define the expected structure of such an object (i.e. the keys and their expected data types) like so:
export interface IRegion { description: Array; } export interface IRegionDescription { id: number; region: string; summary: string; }
Here what we have done is very simple – created the following 2 interfaces (FYI: the generally accepted convention for naming interfaces is to prefix the name with a capitalised:
We begin with the IRegion interface which defines the expected data type for the description property within the returned data (which will be an Array type). Notice that we created a second interface named IRegionDescription to describe the structure of the data for that array? We then use this to help explain the structure for the property value within the IRegion interface.
By using interfaces we can describe the expected structure of our object be defining both their properties and their expected data types (I.e. string, number, boolean, array etc).
What if we encounter a situation where some of those properties might be present in some returned objects but not others?
In TypeScript these are referred to as optional properties and can be handled using the ? operator like so:
export interface IRegionDescription { id?: number; region?: string; summary?: string; }
Typically I define my interfaces in separate files and store these within their own interfaces sub-directory within the Ionic applications’ src directory. This allows me to separate my interfaces into one easily identifiable, central location making them easier to manage in the long run (it also keeps my code DRY – Don’t Repeat Yourself – which I appreciate as a developer striving for good practice).
Alternatively you might prefer to store your interfaces within your TypeScript files above the class where they will be used.
Either approach is fine and I’ll demonstrate both below.
Within my ionic-project/src/interfaces directory I create a TypeScript file named interface.region.ts which is structured as follows:
export interface IRegion { description: Array; } export interface IRegionDescription { id: number; region: string; summary: string; }
This is then imported into the class where it needs to be used with the following import statement:
import { IRegion } from '../../interfaces/interface.region';
We then implement this interface using type assertion to instruct Angular’s HttpClient class on the expected data structure for the returned Observable:
public requestSpecificArea(lat : number, lng : number) : Observable { return this.http.get(this._api + `locate-neighbourhood?q=${lat},${lng}`); }
This then allows the data to be returned and parsed without throwing up any property not found errors.
If you prefer to define your interface within the class where it will be used simply do so as follows ABOVE the class definition like so:
export interface IRegion { description: Array; } export interface IRegionDescription { id: number; region: string; summary: string; } @Injectable() export class YourPageComponentClassOrProvider { }
For more information and to build Mobile app using Ionic, Hire Ionic Developer from us as we give you high quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop the custom mob app using Ionic, please visit our technology page.
Content Source:
57 Sherway St,
Stoney Creek, ON
L8J 0J3
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
57 Sherway St,
Stoney Creek, ON
L8J 0J3
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
© 2025 — HK Infosoft. All Rights Reserved.
© 2025 — HK Infosoft. All Rights Reserved.
T&C | Privacy Policy | Sitemap