Siava Pro

Siava Pro

1622190562

Tips About Accounting For Business Transactions

If you are a small business owner, you know about the many advantages of having a published tax return, such as the IRS’ tiptop audit policy. The audit policy forces taxpayers to post the latest federal income tax return. Recently, some small business owners discovered the many benefits that they can enjoy if they have a printed tax return. These are the advantages of the IRS’s published tax refund and audit policy:

According to the IRS, “auditors will be limited to assessing amounts of income or loss that relate to the taxpayer’s portion of the transaction with the buyer or vendor.” This means that the audit policy protects you against most errors, if not all, which common audit mistakes can make. Also, if you have submitted the required documents, then the audit policy covers those documents too. You may be surprised to learn that you can get relief from most audit situations if you have submitted all necessary documents and made timely payments on your taxes.

Improve Your Tax Credit Score. If you have a good tax credit score, you can get significant tax relief from any potential audit. The audit policy enables the IRS to waive specific audit assessments if the taxpayer can demonstrate that the error resulted from a misunderstanding of the tax code or legislation. Furthermore, the audit policy may also be used to challenge the validity of the initial audit if there is proof that the taxpayer repeatedly failed to provide the necessary documentation or did not respond to the request for documentation promptly.

Save Time and Money. If you are a accounting for business owner, you know that keeping track of your tax liabilities and tax payments is very time-consuming. Furthermore, doing so may cause you severe financial harm, mainly if you receive a notice of audit before you are due at the applicable tax obligation. The audit process can consume valuable time and resources that you (and ultimately your small business). By being adequately prepared, you will handle your small business finances better and reduce the risk of an audit.

Be Proactive With Your Audit Policy. Although the IRS has stated that it will not conduct future audits of past due taxpayers, that does not mean that you are free to ignore an audit notification simply. The audit policy clearly outlines the process and the basis for denial of deductions and other claims. When an audit triggers your TiPS about accounting for business transactions, you should immediately contact the taxpayer and make arrangements to meet with the auditor.

In some cases, the audit may result in a rejection of deductions. As long as you follow the processes outlined in your policy, the inspector will have no reason to issue a rejection letter. However, it is essential to remember that the IRS reserves the right to initiate additional collection actions such as wage garnishment, liens, and bankruptcy. If you find yourself in such a situation, you should consult with a qualified tax attorney to discuss your options. The professional will inform you of the best way to respond to the audit notification and avoid facing potentially harmful tax debt litigation.

#accounting for business

What is GEEK

Buddha Community

Tips About Accounting For Business Transactions
Carmen  Grimes

Carmen Grimes

1595491178

Best Electric Bikes and Scooters for Rental Business or Campus Facility

The electric scooter revolution has caught on super-fast taking many cities across the globe by storm. eScooters, a renovated version of old-school scooters now turned into electric vehicles are an environmentally friendly solution to current on-demand commute problems. They work on engines, like cars, enabling short traveling distances without hassle. The result is that these groundbreaking electric machines can now provide faster transport for less — cheaper than Uber and faster than Metro.

Since they are durable, fast, easy to operate and maintain, and are more convenient to park compared to four-wheelers, the eScooters trend has and continues to spike interest as a promising growth area. Several companies and universities are increasingly setting up shop to provide eScooter services realizing a would-be profitable business model and a ready customer base that is university students or residents in need of faster and cheap travel going about their business in school, town, and other surrounding areas.

Electric Scooters Trends and Statistics

In many countries including the U.S., Canada, Mexico, U.K., Germany, France, China, Japan, India, Brazil and Mexico and more, a growing number of eScooter users both locals and tourists can now be seen effortlessly passing lines of drivers stuck in the endless and unmoving traffic.

A recent report by McKinsey revealed that the E-Scooter industry will be worth― $200 billion to $300 billion in the United States, $100 billion to $150 billion in Europe, and $30 billion to $50 billion in China in 2030. The e-Scooter revenue model will also spike and is projected to rise by more than 20% amounting to approximately $5 billion.

And, with a necessity to move people away from high carbon prints, traffic and congestion issues brought about by car-centric transport systems in cities, more and more city planners are developing more bike/scooter lanes and adopting zero-emission plans. This is the force behind the booming electric scooter market and the numbers will only go higher and higher.

Companies that have taken advantage of the growing eScooter trend develop an appthat allows them to provide efficient eScooter services. Such an app enables them to be able to locate bike pick-up and drop points through fully integrated google maps.

List of Best Electric Bikes for Rental Business or Campus Facility 2020:

It’s clear that e scooters will increasingly become more common and the e-scooter business model will continue to grab the attention of manufacturers, investors, entrepreneurs. All this should go ahead with a quest to know what are some of the best electric bikes in the market especially for anyone who would want to get started in the electric bikes/scooters rental business.

We have done a comprehensive list of the best electric bikes! Each bike has been reviewed in depth and includes a full list of specs and a photo.

Billy eBike

mobile-best-electric-bikes-scooters https://www.kickstarter.com/projects/enkicycles/billy-were-redefining-joyrides

To start us off is the Billy eBike, a powerful go-anywhere urban electric bike that’s specially designed to offer an exciting ride like no other whether you want to ride to the grocery store, cafe, work or school. The Billy eBike comes in 4 color options – Billy Blue, Polished aluminium, Artic white, and Stealth black.

Price: $2490

Available countries

Available in the USA, Europe, Asia, South Africa and Australia.This item ships from the USA. Buyers are therefore responsible for any taxes and/or customs duties incurred once it arrives in your country.

Features

  • Control – Ride with confidence with our ultra-wide BMX bars and a hyper-responsive twist throttle.
  • Stealth- Ride like a ninja with our Gates carbon drive that’s as smooth as butter and maintenance-free.
  • Drive – Ride further with our high torque fat bike motor, giving a better climbing performance.
  • Accelerate – Ride quicker with our 20-inch lightweight cutout rims for improved acceleration.
  • Customize – Ride your own way with 5 levels of power control. Each level determines power and speed.
  • Flickable – Ride harder with our BMX /MotoX inspired geometry and lightweight aluminum package

Specifications

  • Maximum speed: 20 mph (32 km/h)
  • Range per charge: 41 miles (66 km)
  • Maximum Power: 500W
  • Motor type: Fat Bike Motor: Bafang RM G060.500.DC
  • Load capacity: 300lbs (136kg)
  • Battery type: 13.6Ah Samsung lithium-ion,
  • Battery capacity: On/off-bike charging available
  • Weight: w/o batt. 48.5lbs (22kg), w/ batt. 54lbs (24.5kg)
  • Front Suspension: Fully adjustable air shock, preload/compression damping /lockout
  • Rear Suspension: spring, preload adjustment
  • Built-in GPS

Why Should You Buy This?

  • Riding fun and excitement
  • Better climbing ability and faster acceleration.
  • Ride with confidence
  • Billy folds for convenient storage and transportation.
  • Shorty levers connect to disc brakes ensuring you stop on a dime
  • belt drives are maintenance-free and clean (no oil or lubrication needed)

**Who Should Ride Billy? **

Both new and experienced riders

**Where to Buy? **Local distributors or ships from the USA.

Genze 200 series e-Bike

genze-best-electric-bikes-scooters https://www.genze.com/fleet/

Featuring a sleek and lightweight aluminum frame design, the 200-Series ebike takes your riding experience to greater heights. Available in both black and white this ebike comes with a connected app, which allows you to plan activities, map distances and routes while also allowing connections with fellow riders.

Price: $2099.00

Available countries

The Genze 200 series e-Bike is available at GenZe retail locations across the U.S or online via GenZe.com website. Customers from outside the US can ship the product while incurring the relevant charges.

Features

  • 2 Frame Options
  • 2 Sizes
  • Integrated/Removable Battery
  • Throttle and Pedal Assist Ride Modes
  • Integrated LCD Display
  • Connected App
  • 24 month warranty
  • GPS navigation
  • Bluetooth connectivity

Specifications

  • Maximum speed: 20 mph with throttle
  • Range per charge: 15-18 miles w/ throttle and 30-50 miles w/ pedal assist
  • Charging time: 3.5 hours
  • Motor type: Brushless Rear Hub Motor
  • Gears: Microshift Thumb Shifter
  • Battery type: Removable Samsung 36V, 9.6AH Li-Ion battery pack
  • Battery capacity: 36V and 350 Wh
  • Weight: 46 pounds
  • Derailleur: 8-speed Shimano
  • Brakes: Dual classic
  • Wheels: 26 x 20 inches
  • Frame: 16, and 18 inches
  • Operating Mode: Analog mode 5 levels of Pedal Assist Thrott­le Mode

Norco from eBikestore

norco-best-electric-bikes-scooters https://ebikestore.com/shop/norco-vlt-s2/

The Norco VLT S2 is a front suspension e-Bike with solid components alongside the reliable Bosch Performance Line Power systems that offer precise pedal assistance during any riding situation.

Price: $2,699.00

Available countries

This item is available via the various Norco bikes international distributors.

Features

  • VLT aluminum frame- for stiffness and wheel security.
  • Bosch e-bike system – for their reliability and performance.
  • E-bike components – for added durability.
  • Hydraulic disc brakes – offer riders more stopping power for safety and control at higher speeds.
  • Practical design features – to add convenience and versatility.

Specifications

  • Maximum speed: KMC X9 9spd
  • Motor type: Bosch Active Line
  • Gears: Shimano Altus RD-M2000, SGS, 9 Speed
  • Battery type: Power Pack 400
  • Battery capacity: 396Wh
  • Suspension: SR Suntour suspension fork
  • Frame: Norco VLT, Aluminum, 12x142mm TA Dropouts

Bodo EV

bodo-best-electric-bikes-scootershttp://www.bodoevs.com/bodoev/products_show.asp?product_id=13

Manufactured by Bodo Vehicle Group Limited, the Bodo EV is specially designed for strong power and extraordinary long service to facilitate super amazing rides. The Bodo Vehicle Company is a striking top in electric vehicles brand field in China and across the globe. Their Bodo EV will no doubt provide your riders with high-level riding satisfaction owing to its high-quality design, strength, breaking stability and speed.

Price: $799

Available countries

This item ships from China with buyers bearing the shipping costs and other variables prior to delivery.

Features

  • Reliable
  • Environment friendly
  • Comfortable riding
  • Fashionable
  • Economical
  • Durable – long service life
  • Braking stability
  • LED lighting technology

Specifications

  • Maximum speed: 45km/h
  • Range per charge: 50km per person
  • Charging time: 8 hours
  • Maximum Power: 3000W
  • Motor type: Brushless DC Motor
  • Load capacity: 100kg
  • Battery type: Lead-acid battery
  • Battery capacity: 60V 20AH
  • Weight: w/o battery 47kg

#android app #autorent #entrepreneurship #ios app #minimum viable product (mvp) #mobile app development #news #app like bird #app like bounce #app like lime #autorent #best electric bikes 2020 #best electric bikes for rental business #best electric kick scooters 2020 #best electric kickscooters for rental business #best electric scooters 2020 #best electric scooters for rental business #bird scooter business model #bird scooter rental #bird scooter rental cost #bird scooter rental price #clone app like bird #clone app like bounce #clone app like lime #electric rental scooters #electric scooter company #electric scooter rental business #how do you start a moped #how to start a moped #how to start a scooter rental business #how to start an electric company #how to start electric scooterrental business #lime scooter business model #scooter franchise #scooter rental business #scooter rental business for sale #scooter rental business insurance #scooters franchise cost #white label app like bird #white label app like bounce #white label app like lime

Carmen  Grimes

Carmen Grimes

1595494844

How to start an electric scooter facility/fleet in a university campus/IT park

Are you leading an organization that has a large campus, e.g., a large university? You are probably thinking of introducing an electric scooter/bicycle fleet on the campus, and why wouldn’t you?

Introducing micro-mobility in your campus with the help of such a fleet would help the people on the campus significantly. People would save money since they don’t need to use a car for a short distance. Your campus will see a drastic reduction in congestion, moreover, its carbon footprint will reduce.

Micro-mobility is relatively new though and you would need help. You would need to select an appropriate fleet of vehicles. The people on your campus would need to find electric scooters or electric bikes for commuting, and you need to provide a solution for this.

To be more specific, you need a short-term electric bike rental app. With such an app, you will be able to easily offer micro-mobility to the people on the campus. We at Devathon have built Autorent exactly for this.

What does Autorent do and how can it help you? How does it enable you to introduce micro-mobility on your campus? We explain these in this article, however, we will touch upon a few basics first.

Micro-mobility: What it is

micro-mobility

You are probably thinking about micro-mobility relatively recently, aren’t you? A few relevant insights about it could help you to better appreciate its importance.

Micro-mobility is a new trend in transportation, and it uses vehicles that are considerably smaller than cars. Electric scooters (e-scooters) and electric bikes (e-bikes) are the most popular forms of micro-mobility, however, there are also e-unicycles and e-skateboards.

You might have already seen e-scooters, which are kick scooters that come with a motor. Thanks to its motor, an e-scooter can achieve a speed of up to 20 km/h. On the other hand, e-bikes are popular in China and Japan, and they come with a motor, and you can reach a speed of 40 km/h.

You obviously can’t use these vehicles for very long commutes, however, what if you need to travel a short distance? Even if you have a reasonable public transport facility in the city, it might not cover the route you need to take. Take the example of a large university campus. Such a campus is often at a considerable distance from the central business district of the city where it’s located. While public transport facilities may serve the central business district, they wouldn’t serve this large campus. Currently, many people drive their cars even for short distances.

As you know, that brings its own set of challenges. Vehicular traffic adds significantly to pollution, moreover, finding a parking spot can be hard in crowded urban districts.

Well, you can reduce your carbon footprint if you use an electric car. However, electric cars are still new, and many countries are still building the necessary infrastructure for them. Your large campus might not have the necessary infrastructure for them either. Presently, electric cars don’t represent a viable option in most geographies.

As a result, you need to buy and maintain a car even if your commute is short. In addition to dealing with parking problems, you need to spend significantly on your car.

All of these factors have combined to make people sit up and think seriously about cars. Many people are now seriously considering whether a car is really the best option even if they have to commute only a short distance.

This is where micro-mobility enters the picture. When you commute a short distance regularly, e-scooters or e-bikes are viable options. You limit your carbon footprints and you cut costs!

Businesses have seen this shift in thinking, and e-scooter companies like Lime and Bird have entered this field in a big way. They let you rent e-scooters by the minute. On the other hand, start-ups like Jump and Lyft have entered the e-bike market.

Think of your campus now! The people there might need to travel short distances within the campus, and e-scooters can really help them.

How micro-mobility can benefit you

benefits-micromobility

What advantages can you get from micro-mobility? Let’s take a deeper look into this question.

Micro-mobility can offer several advantages to the people on your campus, e.g.:

  • Affordability: Shared e-scooters are cheaper than other mass transportation options. Remember that the people on your campus will use them on a shared basis, and they will pay for their short commutes only. Well, depending on your operating model, you might even let them use shared e-scooters or e-bikes for free!
  • Convenience: Users don’t need to worry about finding parking spots for shared e-scooters since these are small. They can easily travel from point A to point B on your campus with the help of these e-scooters.
  • Environmentally sustainable: Shared e-scooters reduce the carbon footprint, moreover, they decongest the roads. Statistics from the pilot programs in cities like Portland and Denver showimpressive gains around this key aspect.
  • Safety: This one’s obvious, isn’t it? When people on your campus use small e-scooters or e-bikes instead of cars, the problem of overspeeding will disappear. you will see fewer accidents.

#android app #autorent #ios app #mobile app development #app like bird #app like bounce #app like lime #autorent #bird scooter business model #bird scooter rental #bird scooter rental cost #bird scooter rental price #clone app like bird #clone app like bounce #clone app like lime #electric rental scooters #electric scooter company #electric scooter rental business #how do you start a moped #how to start a moped #how to start a scooter rental business #how to start an electric company #how to start electric scooterrental business #lime scooter business model #scooter franchise #scooter rental business #scooter rental business for sale #scooter rental business insurance #scooters franchise cost #white label app like bird #white label app like bounce #white label app like lime

Why Business Cards Printing are essential for your business

No matter how technological advancement helps in communication but business card printing still worth it. Most businesses prefer to have and share business cards to develop a direct relationship with the potential market. It is an important part of the promotional and branding strategy and effectively described the brand’s nature. It gives ease in sharing the business-related information in the public like at conference, workshops and other.

This is image title

Moreover, a quality visiting card printing online provides the impression of products or services. According to the random research, it is stated that most of the customers draw the conclusion about the business and its products from the card quality or its printing. So, a smart business card with the right size and content is essential for the business.

Here are the factors that will help to understand the importance of the business card in the brand promotion or more:

Provide Contact Details:

One of the main reasons behind business card printing is the contact sharing features. The card contains contact details, name, logo, and other related information that helps the client to reach the business. Further, it helps to describe the brand or product nature before approaching the product or services. Other than the technology usage or sharing of the information through devices, business cards are most suitable and a handy item that worth a lot for the customers.

This is image title

The impression of the Brand:

The business card is a source that will deliver the first impression of the brand or business towards the potential buyers. It is something handy with the physical touch that develops a direct relationship with the potential market. While going to print business cards that quality, printing style, and overall outlook matters a lot. Because it works as the first impression of the business and its product or services for the potential market. So, the worthy card made with durable material and have an attractive color combination or layout can capture the interest easily.

It contains the company logo, name, design, and color combination that quickly attain the interest of the audience. On other hand, it is an important factor to pay attention to while making the designing and printing decision about the business card.

Direct Marketing Facility:

No doubt there are multiple marketing and promotional tools are available for the product or business promotion. But engraved business cards online is something incredible and handy that provide the physical touch experience. It works as the marketing or promotional element that helps in sharing the details directly to the potential market. With the more physical interaction that the business cards offer to the buyers and business.

The important thing that has to be considered in making the custom business cards, related to the content adjustment, design, and color combination. It helps to capture the buyer’s interest and deliver the right impression towards them.

This is image title

Appreciated in Different Cultures:

The business cards preferably deliver the right knowledge and impression about the product or services. It described the brand position, nature of the products or services, and other relevant skills. In most cultures, it is appreciated to have and share physical business cards as an information-sharing tool. In face-to-face interaction, develops a network and promotes sharing the business information in a circle.

Ease to Provide a Business Reference:

In business cards, online people find multiple opportunities in designing and Printing Services with a significant impression. It helps to make an easy referral related to particular services and a person with a skill set. The business car not only contains the address, contact information, or brand-related knowledge. It provides details about the particular person and reflects the skill set. Multiple factors truly help to describe the right impression of the brand through color, text, and images.

A tool to Develop Trust:

For business growth and development, it is important to gain the trust level of the customers. With the custom business cards, it is easier to attain the trust of the customers. in the competitive business atmosphere for a business survival trust is the only key, that can be over the product or on a company as well. Through the business card, it is easier to exchange and share personal warmth feelings.

With Business Cards Printing, it is easier to show more graphical representation through colors and design. Moreover, with the physical touch, it is easier to give trust feelings or more.

This is image title

Final Consideration!

In the competitive business world, the business card is a source to deliver information and capture the interest of potential buyers. It helps to impress the audience and provide relevant product details and skills that build trust or act as the direct promotional tool.

#business cards printing #visiting card printing online #go print business cards #engraved business cards online #custom business cards #business cards online

中條 美冬

1646489880

Angularを使用したCrudWebアプリの構築| Angular 13 CRUD

Angular CRUDとは、データ機能の作成、読み取り、更新、削除で構成されるアプリケーションを意味します。これは、新しいAngularフレームワークを使用してCRUD(作成、読み取り、更新、削除)Webアプリケーションを構築するための包括的なガイドです。Angularがリリースされたばかりで、いくつかの新機能と改善が含まれています。

まず、Angular CLIを使用してAngularをインストールし、次にフロントエンドとバックエンドの開発を続けます。

1:Angularおよびその他の依存関係をインストールします。

古い@angular / cliバージョンを使用している場合は、次のコマンドを実行して最新バージョンをインストールできます。

npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli

問題が発生した場合は、AngularCLIをバージョン7に更新する方法を確認してください。 Angular CLIを更新するのに役立ち、まったく新しいAngularsevenプロジェクトを作成します。

さて、次のコマンドを入力すると、 AngularCLIが更新されたことがわかります。

Angular 7CRUDの例|  MEANスタックチュートリアル

次に、次のコマンドを使用して新しいAngularプロジェクトを作成します。

ng new angular7crud
cd angular7crud

MEANスタックCRUDの例

プロジェクトフォルダー内に入った後、次のコマンドを使用してVisual StudioCodeでプロジェクトを開きます。使用していない場合は、使用を開始してください。これは、 Javascript開発に最適なエディターです。

code .

インストール時に、アプリケーションのルーティングを有効にしました。 Angularボイラープレートの取り付け中にプロンプ​​トが表示されるため、 Angularの新機能です。src >> appディレクトリ内のapp-routing.module.ts ファイルと呼ばれるファイルを確認できます。

次に、次のコマンドを使用してBootstrap 4 CSSFramework をインストールします。

npm install bootstrap --save

次に、 angular.json ファイル内に追加し ます。

"styles": [
   "src/styles.css",
   "./node_modules/bootstrap/dist/css/bootstrap.min.css"
 ],

これで、プロジェクトでBootstrap4クラスを使用できるようになりました。 

次のコマンドを使用して、Angular開発サーバーを起動します。

ng serve -o

 

Angular7ウォークスルー

プロジェクトの説明

ユーザーがフォームからユーザー 名、会社名、  GST番号を入力して送信できるプロジェクトを作成します。値が正しくない場合、フロントエンドで検証され、フォームは送信されません。一方、すべての値が完全であると思われる場合は、フォームをバックエンドAPIに送信し、 MongoDBデータベース内に値を保存します。

それで、今、私たちは仕事をするためにいくつかの角度のあるコンポーネントを作成します。

2:Angularコンポーネントを生成する

次のコマンドを入力して、Angularコンポーネントを生成します。作成、読み取り、更新の操作を行います。したがって、3つのコンポーネントを作成します。

ng g c gst-add --spec=false
ng g c gst-get --spec=false
ng g c gst-edit --spec=false

AngularCRUDチュートリアル

3つのコンポーネントはすべて、app.module.ts ファイル内に自動的に登録されます。app-routing.module.ts ファイル内でAngularコンポーネントのルーティングを構成する必要があります。

// app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { GstAddComponent } from './gst-add/gst-add.component';
import { GstEditComponent } from './gst-edit/gst-edit.component';
import { GstGetComponent } from './gst-get/gst-get.component';

const routes: Routes = [
  {
    path: 'business/create',
    component: GstAddComponent
  },
  {
    path: 'business/edit/:id',
    component: GstEditComponent
  },
  {
    path: 'business',
    component: GstGetComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

export class AppRoutingModule { }

これで、  app.component.html ファイル内に<router-outlet> ディレクティブがあることがわかります。このディレクティブは、ルートURIに基づいてさまざまなコンポーネントをレンダリングするのに役立ちます。

3:角度ナビゲーションを作成する

app.component.html ファイル内に次のコードを 記述します。

<nav class="navbar navbar-expand-sm bg-light">
  <div class="container-fluid">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a routerLink="business/create" class="nav-link" routerLinkActive="active">
          Create Business
        </a>
      </li>
      <li class="nav-item">
        <a routerLink="business" class="nav-link" routerLinkActive="active">
          Business
        </a>
      </li> 
    </ul>
  </div>
</nav>

<div class="container">
  <router-outlet></router-outlet>
</div>

ファイルを保存してブラウザに移動し、2つのリンクをクリックします。ナビゲーションに基づいてさまざまなコンポーネントを確認できることがわかります。

4:Angular Routing ProgressIndicatorをインストールします。

次のコマンドを入力して、  ng2-slim-loading-barライブラリをインストールします。

npm install ng2-slim-loading-bar --save

そのため、今すぐサードパーティのパッケージをインストールすると、Angularと互換性がなくなります。Angular パッケージとサードパーティパッケージの間のギャップを埋める ために、次のライブラリをインストールする必要があります。それだ。

npm install rxjs-compat --save

次に、 app.module.ts ファイル内に SlimLoadingBarModule をインポートし ます。

// app.module.ts

import { SlimLoadingBarModule } from 'ng2-slim-loading-bar';

imports: [
    ...
    SlimLoadingBarModule
],

次のステップは、 src >> styles.css ファイル内にライブラリを使用したスタイル設定を含めることです。

@import "../node_modules/ng2-slim-loading-bar/style.css";

5:ルーターイベントの追加。

Angular RouterModuleは、次のイベントモジュールを提供します。

  1. NavigationStart
  2. NavigationEnd
  3. NavigationError
  4. NavigationCancel
  5. ルーター
  6. イベント

次に、 app.component.ts ファイル内に次のコードを記述し  ます。

// app.component.ts

import { Component } from '@angular/core';
import {SlimLoadingBarService} from 'ng2-slim-loading-bar';
import { NavigationCancel,
        Event,
        NavigationEnd,
        NavigationError,
        NavigationStart,
        Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular7crud';
  constructor(private _loadingBar: SlimLoadingBarService, private _router: Router) {
    this._router.events.subscribe((event: Event) => {
      this.navigationInterceptor(event);
    });
  }
  private navigationInterceptor(event: Event): void {
    if (event instanceof NavigationStart) {
      this._loadingBar.start();
    }
    if (event instanceof NavigationEnd) {
      this._loadingBar.complete();
    }
    if (event instanceof NavigationCancel) {
      this._loadingBar.stop();
    }
    if (event instanceof NavigationError) {
      this._loadingBar.stop();
    }
  }
}

ルーティングイベントをインターセプトし、すべてのルートにローディングバーコンポーネントを追加して、ルートを変更するたびにルーティング表示を確認できるようにします。

ルーティングインジケータを表示するための最後の変更は、ページ上部のapp.component.html ファイル内にng2-slim-loading-barディレクティブ を追加することです。

<ng2-slim-loading-bar color="blue"></ng2-slim-loading-bar>

<nav class="navbar navbar-expand-sm bg-light">
  <div class="container-fluid">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a routerLink="business/create" class="nav-link" routerLinkActive="active">
          Create Business
        </a>
      </li>
      <li class="nav-item">
        <a routerLink="business" class="nav-link" routerLinkActive="active">
          Business
        </a>
      </li> 
    </ul>
  </div>
</nav>

<div class="container">
  <router-outlet></router-outlet>
</div>

ファイルを保存してターミナルに移動し、エラーがあるかどうかを確認します。エラーがない場合は、ブラウザに移動してルートを変更します。これで、ルーティングインジケータが表示されることがわかります。

6:ブートストラップフォームを追加する

gst-add.component.html ファイル 内 に、次のブートストラップ4フォームを追加します。

<div class="card">
  <div class="card-body">
    <form>
      <div class="form-group">
        <label class="col-md-4">Person Name</label>
        <input type="text" class="form-control" />
      </div>
      <div class="form-group">
        <label class="col-md-4">Business Name </label>
        <input type="text" class="form-control" />
      </div>
      <div class="form-group">
        <label class="col-md-4">Business GST Number </label>
        <input type="text" class="form-control" />
      </div>
      <div class="form-group">
        <button type="submit" class="btn btn-primary">Add Business</button>
      </div>
    </form>
  </div>
</div>

Angular 7CRUDデモ

7:Angularフォーム検証を追加する

ReactiveFormsModuleを使用します。したがって、 Angular Form Validationを初めて使用する場合は、このブログのこの記事Angular FormValidationを確認してください 

次に、 app.module.ts ファイル内に ReactiveFormsModule をインポートし ます。

// app.module.ts

import { ReactiveFormsModule } from '@angular/forms';

imports: [
    ...
    ReactiveFormsModule
],

次に、 app.component.ts ファイルのコードを作成する必要があり ます。これはテンプレート駆動型のフォームではないことを忘れないでください。そのため、 app.component.ts ファイル内のコードを変更します。

まず、  FormGroup、FormBuilder、Validators モジュールを @ angle / formsからインポートします。

また、コンストラクターを作成し、  FormBuilderをインスタンス化します。

したがって、 gst-add.component.ts ファイル内に次のコードを記述し ます。

// gst-add.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';

@Component({
  selector: 'app-gst-add',
  templateUrl: './gst-add.component.html',
  styleUrls: ['./gst-add.component.css']
})
export class GstAddComponent implements OnInit {

  angForm: FormGroup;
  constructor(private fb: FormBuilder) {
    this.createForm();
  }

  createForm() {
    this.angForm = this.fb.group({
      person_name: ['', Validators.required ],
      business_name: ['', Validators.required ],
      business_gst_number: ['', Validators.required ]
    });
  }

  ngOnInit() {
  }

}

フォームビルダーを使用してすべての検証を処理しました。そのため、そのコンストラクターでは、検証ルールを使用してフォームを作成しています。この例では、3つのフィールドがあります。入力テキストが空の場合、エラーが発生するため、表示する必要があります。

ここで、 gst-add.component.html ファイル内に次のコードを記述し ます。

<div class="card">
  <div class="card-body">
    <form [formGroup]="angForm" novalidate>
      <div class="form-group">
        <label class="col-md-4">Person Name</label>
        <input type="text" class="form-control" formControlName="person_name" #person_name />
      </div>
      <div *ngIf="angForm.controls['person_name'].invalid && (angForm.controls['person_name'].dirty || angForm.controls['person_name'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['person_name'].errors.required">
          Person Name is required.
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-4">Business Name </label>
        <input type="text" class="form-control" formControlName="business_name" #business_name />
      </div>
      <div *ngIf="angForm.controls['business_name'].invalid && (angForm.controls['business_name'].dirty || angForm.controls['business_name'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['business_name'].errors.required">
          Person Business is required.
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-4">Business GST Number </label>
        <input type="text" class="form-control" formControlName="business_gst_number" #business_gst_number />
      </div>
      <div *ngIf="angForm.controls['business_gst_number'].invalid && (angForm.controls['business_gst_number'].dirty || angForm.controls['business_gst_number'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['business_gst_number'].errors.required">
          Business GST Number is required.
        </div>
      </div>
      <div class="form-group">
        <button type="submit" 
        [disabled]="angForm.pristine || angForm.invalid" 
        class="btn btn-primary">Add Business</button>
      </div>
    </form>
  </div>
</div>

ファイルを保存してブラウザに移動すると、入力ボックスに値を入力しないかどうかを確認でき、エラーが表示されます。

Angular7フォーム検証の例

8:HttpClientModuleを構成します

app.module.ts ファイル内に HttpClientModule をインポートし ます。

// app.module.ts

import { HttpClientModule } from '@angular/common/http';

imports: [
   ...
    HttpClientModule
 ],

9:モデルを作成します。

src >> app フォルダー内 に、 Business.ts というファイルを1つ作成 し、次のコードを追加します。

// Business.ts

export default class Business {
  person_name: String;
  business_name: String;
  business_gst_number: Number;
}

10:AngularServiceファイルを作成します。

次のコマンドを入力して、サービスファイルを生成します。

ng g service business --spec=false

したがって、プライマリ business.service.ts ファイルは次のようになります。

// business.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class BusinessService {

  constructor() { }
}

次に、 business.service.ts ファイルを app.module.ts ファイルにインポートし ます。

// app.module.ts

import { BusinessService } from './business.service';

providers: [ BusinessService ],

11:データをノードサーバーに送信します

データを含むHTTPPOSTリクエストをNode.jsサーバーに送信し、データをMongoDBデータベースに保存するコードを作成する必要があります。

business.service.ts ファイル内に次のコードを記述し ます。

// business.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class BusinessService {

  uri = 'http://localhost:4000/business';

  constructor(private http: HttpClient) { }

  addBusiness(person_name, business_name, business_gst_number) {
    const obj = {
      person_name: person_name,
      business_name: business_name,
      business_gst_number: business_gst_number
    };
    console.log(obj);
    this.http.post(`${this.uri}/add`, obj)
        .subscribe(res => console.log('Done'));
  }
}

バックエンドAPIURLを定義しましたが、まだバックエンドを作成していませんが、いくつかの手順で作成します。

クリックイベントを[ビジネスの追加]ボタンに追加する必要があります。したがって、 gst-add.component.html ファイル内に次のコードを追加します。

<div class="form-group">
    <button (click)="addBusiness(person_name.value, business_name.value, business_gst_number.value)"
        [disabled]="angForm.pristine || angForm.invalid" 
        class="btn btn-primary">
        Add Business
     </button>
</div>

したがって、エラーがない場合は、フォームを送信すると、コンポーネントの addBusiness 関数が呼び出されます。そこから、Angularサービスを呼び出し、サービスはHTTPPostリクエストをNode.jsサーバーに送信します。

次に、 gst-add.component.ts ファイル内にaddBusiness 関数を 追加し ます。したがって、gst-add.component.ts ファイル内に次のコードを記述し ます。

// gst-add.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';
import { BusinessService } from '../business.service';

@Component({
  selector: 'app-gst-add',
  templateUrl: './gst-add.component.html',
  styleUrls: ['./gst-add.component.css']
})
export class GstAddComponent implements OnInit {

  angForm: FormGroup;
  constructor(private fb: FormBuilder, private bs: BusinessService) {
    this.createForm();
  }

  createForm() {
    this.angForm = this.fb.group({
      person_name: ['', Validators.required ],
      business_name: ['', Validators.required ],
      business_gst_number: ['', Validators.required ]
    });
  }

  addBusiness(person_name, busines_name, business_gst_number) {
    this.bs.addBusiness(person_name, busines_name, business_gst_number);
  }

  ngOnInit() {
  }

}

ここでは、関数を定義し、  business.service.ts ファイルもインポートしました。次に、コンストラクター内でオブジェクトをインスタンス化し、businsess.service.tsファイルの関数を呼び出します。

addBusiness 関数は business.service.ts ファイル内にすでにコーディングされてい ます。次に、バックエンドAPIを構成する必要があります。

12:Node.jsバックエンドAPIを作成します

角度ルートフォルダー内に、apiというフォルダーを1つ作成し、そのフォルダー内に移動します。Angularとは完全に別のプロジェクトになることを忘れないでください。そのため、そのnode_modulesはAngularとは異なります。

api フォルダー内のターミナルを開き、 次のコマンドを入力します。

npm init -y

次のノード固有のモジュールをインストールします。

npm install --save express body-parser cors mongoose

毎回ノードサーバーを再起動するわけではありません。ファイルを変更します。だから私はnodemonサーバーをインストールしています。 server.js ファイルを変更すると、 node.jsサーバー が自動的に再起動し ます。

npm install nodemon --save-dev

次に、  api フォルダー内に、  server.js ファイルと呼ばれる1つのファイルを作成します。

// server.js

const express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    mongoose = require('mongoose');

    const app = express();
    let port = process.env.PORT || 4000;

    const server = app.listen(function(){
        console.log('Listening on port ' + port);
    });

次に、MongoDBデータベースをnode.jsアプリケーションに接続します。

MongoDBデータベースをインストールしていない場合は、インストールしてmongodbサーバーを起動します。

次のコマンドを入力して、  MongoDB サーバーを起動します。

mongod

これで、データベースに接続しました。

api ルートプロジェクトフォルダー 内に DB.jsというファイルを1つ作成 します。次に、DB.js ファイル内に次のコードを記述します。

// DB.js

module.exports = {
    DB: 'mongodb://localhost:27017/ng7crud'
 };

この DB.jsファイルをserver.js ファイル内に インポートし、mongooseライブラリを使用 してMongoDBとのデータベース接続 を  セットアップし ます。Mongooseを使用して、MongooseORMを使用してデータベースにデータを保存することもできます。

server.js ファイル 内に次のコードを記述して、 MongoDB アプリケーションを Node.js サーバーに接続します。

// server.js

const express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    mongoose = require('mongoose'),
    config = require('./DB');

    mongoose.Promise = global.Promise;
    mongoose.connect(config.DB, { useNewUrlParser: true }).then(
      () => {console.log('Database is connected') },
      err => { console.log('Can not connect to the database'+ err)}
    );

    const app = express();
    app.use(bodyParser.json());
    app.use(cors());
    const port = process.env.PORT || 4000;

    const server = app.listen(port, function(){
     console.log('Listening on port ' + port);
    });

ファイルを保存してターミナルに移動し、ノードサーバーを起動します。

nodemon server

したがって、現在、3台のサーバーが実行されています。

  1. Angular Development Server
  2. Nodemonサーバー
  3. MongoDBサーバー

3つのサーバーすべてがエラーなしで正常に実行されていることを忘れないでください。そうしないと、アプリケーションが機能しません。

ステップ13:アプリケーションのモデルとルートを作成します。

ルートモデルと呼ばれるAPI ルート フォルダー内に2つのフォルダーを作成する必要があります。

モデルの フォルダーに、  Business.jsというモデルを1つ作成します。

// Business.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Define collection and schema for Business
let Business = new Schema({
  person_name: {
    type: String
  },
  business_name: {
    type: String
  },
  business_gst_number: {
    type: Number
  }
},{
    collection: 'business'
});

module.exports = mongoose.model('Business', Business);

そこで、ビジネスコレクションのスキーマを定義しました。person_name、business_name、business_gst_numberという3つのフィールドがあります 。

ルート フォルダーに、business.route.jsというファイルを1つ作成します 

business.route.js ファイル内にCRUDコードを記述し ます。

// business.route.js

const express = require('express');
const app = express();
const businessRoutes = express.Router();

// Require Business model in our routes module
let Business = require('../models/Business');

// Defined store route
businessRoutes.route('/add').post(function (req, res) {
  let business = new Business(req.body);
  business.save()
    .then(business => {
      res.status(200).json({'business': 'business in added successfully'});
    })
    .catch(err => {
    res.status(400).send("unable to save to database");
    });
});

// Defined get data(index or listing) route
businessRoutes.route('/').get(function (req, res) {
    Business.find(function (err, businesses){
    if(err){
      console.log(err);
    }
    else {
      res.json(businesses);
    }
  });
});

// Defined edit route
businessRoutes.route('/edit/:id').get(function (req, res) {
  let id = req.params.id;
  Business.findById(id, function (err, business){
      res.json(business);
  });
});

//  Defined update route
businessRoutes.route('/update/:id').post(function (req, res) {
    Business.findById(req.params.id, function(err, next, business) {
    if (!business)
      return next(new Error('Could not load Document'));
    else {
        business.person_name = req.body.person_name;
        business.business_name = req.body.business_name;
        business.business_gst_number = req.body.business_gst_number;

        business.save().then(business => {
          res.json('Update complete');
      })
      .catch(err => {
            res.status(400).send("unable to update the database");
      });
    }
  });
});

// Defined delete | remove | destroy route
businessRoutes.route('/delete/:id').get(function (req, res) {
    Business.findByIdAndRemove({_id: req.params.id}, function(err, business){
        if(err) res.json(err);
        else res.json('Successfully removed');
    });
});

module.exports = businessRoutes;

マングースモデルを使用して、データベースを保存、更新、および削除しました。Mongooseは、 MongoDBデータベースで使用されるORMです。ルートファイルにすべてのCRUD操作を設定しました。それらをserver.js ファイル内にインポートする必要があります。

したがって、最終的な server.js ファイルは次のようになります。

// server.js

const express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    mongoose = require('mongoose'),
    config = require('./DB');

const businessRoute = require('./routes/business.route');
mongoose.Promise = global.Promise;
mongoose.connect(config.DB, { useNewUrlParser: true }).then(
  () => {console.log('Database is connected') },
  err => { console.log('Can not connect to the database'+ err)}
);

const app = express();
app.use(bodyParser.json());
app.use(cors());
app.use('/business', businessRoute);
const port = process.env.PORT || 4000;

const server = app.listen(port, function(){
  console.log('Listening on port ' + port);
});

手順14:データの保存機能をテストする

すべてのサーバーが稼働している場合は、ブラウザーに移動し、フォームデータに入力して、ビジネスを追加できます。成功すると、画面にこのようなものが表示されます。

これで、次のコマンドを使用してデータベースを確認できます。

まず、他の3つのタブがすべて現在使用されているため、4番目のタブでmongoシェルを開きます。

mongo

ここでは、値がMongoDBデータベースに保存されていることがわかります。はい!成功しました。

現在、残りの操作は読み取り、更新、および削除です。

15:フロントエンドにデータを表示します

gst-get.component.html ファイルに、次のコードを記述します。

<table class="table table-hover">
  <thead>
  <tr>
      <td>Person Name</td>
      <td>Business Name</td>
      <td>GST Number</td>
      <td colspan="2">Actions</td>
  </tr>
  </thead>

  <tbody>
      <tr *ngFor="let business of businesses">
          <td>{{ business.person_name }}</td>
          <td>{{ business.business_name }}</td>
          <td>{{ business.business_gst_number }}</td>
          <td><a [routerLink]="['/edit', business._id]" class="btn btn-primary">Edit</a></td>
          <td><a [routerLink]="" class="btn btn-danger">Delete</a></td>
      </tr>
  </tbody>
</table>

ここで、  business.service.ts ファイル内に、 MongoDBデータベースからビジネスデータをフェッチ してAngularアプリケーションに表示する関数を作成する必要があります。

// business.service.ts

getBusinesses() {
    return this
           .http
           .get(`${this.uri}`);
  }

このbusiness.service.ts ファイルとBusiness.ts ファイルをgst-get.component.ts ファイル内 に含める必要があります。

gst-get.component.ts ファイル内に次のコードを 記述します。

// gst-get.component.ts

import { Component, OnInit } from '@angular/core';
import Business from '../Business';
import { BusinessService } from '../business.service';

@Component({
  selector: 'app-gst-get',
  templateUrl: './gst-get.component.html',
  styleUrls: ['./gst-get.component.css']
})
export class GstGetComponent implements OnInit {

  businesses: Business[];

  constructor(private bs: BusinessService) { }

  ngOnInit() {
    this.bs
      .getBusinesses()
      .subscribe((data: Business[]) => {
        this.businesses = data;
    });
  }
}

ファイルを保存し、ブラウザに移動して、次のURLに切り替えます: http:// localhost:4200 / business。 あなたはビジネスのリストを見ることができます。

16:データの編集と更新

まず、_idを使用してMongoDBデータベースからデータをフェッチし、そのデータをgst-edit.component.html ファイルに表示する必要があります。

したがって、最初に、  gst-edit.component.ts ファイル内に次のコードを記述します。

// gst-edit.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';
import { BusinessService } from '../business.service';

@Component({
  selector: 'app-gst-edit',
  templateUrl: './gst-edit.component.html',
  styleUrls: ['./gst-edit.component.css']
})
export class GstEditComponent implements OnInit {

  business: any = {};
  angForm: FormGroup;

  constructor(private route: ActivatedRoute,
    private router: Router,
    private bs: BusinessService,
    private fb: FormBuilder) {
      this.createForm();
 }

  createForm() {
    this.angForm = this.fb.group({
        person_name: ['', Validators.required ],
        business_name: ['', Validators.required ],
        business_gst_number: ['', Validators.required ]
      });
    }


  ngOnInit() {
    this.route.params.subscribe(params => {
        this.bs.editBusiness(params['id']).subscribe(res => {
          this.business = res;
      });
    });
  }
}

ここで、  gst-edit component.ts がレンダリングされると、  ngOnInit メソッドが呼び出され、ノードサーバーにHTTPリクエストが送信され、_idからデータがフェッチされてgst-edit.component.html ファイル内に表示され ます。

ここで、  business.service.ts ファイル 内で、HTTPリクエストを送信するためにeditBusiness 関数をコーディングする必要があります。

// business.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class BusinessService {

  uri = 'http://localhost:4000/business';

  constructor(private http: HttpClient) { }

  addBusiness(person_name, business_name, business_gst_number) {
    const obj = {
      person_name: person_name,
      business_name: business_name,
      business_gst_number: business_gst_number
    };
    this.http.post(`${this.uri}/add`, obj)
        .subscribe(res => console.log('Done'));
  }

  getBusinesses() {
    return this
           .http
           .get(`${this.uri}`);
  }

  editBusiness(id) {
    return this
            .http
            .get(`${this.uri}/edit/${id}`);
    }
}

最後に、gst-edit.component.html ファイル内にフォームを作成する必要があります。

<div class="card">
  <div class="card-body">
    <form [formGroup]="angForm" novalidate>
      <div class="form-group">
        <label class="col-md-4">Person Name</label>
        <input type="text" class="form-control" formControlName="person_name" #person_name [(ngModel)] = "business.person_name" />
      </div>
      <div *ngIf="angForm.controls['person_name'].invalid && (angForm.controls['person_name'].dirty || angForm.controls['person_name'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['person_name'].errors.required">
          Person Name is required.
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-4">Business Name </label>
        <input type="text" class="form-control" formControlName="business_name" #business_name [(ngModel)] = "business.business_name" />
      </div>
      <div *ngIf="angForm.controls['business_name'].invalid && (angForm.controls['business_name'].dirty || angForm.controls['business_name'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['business_name'].errors.required">
          Person Business is required.
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-4">Business GST Number </label>
        <input type="text" class="form-control" formControlName="business_gst_number" #business_gst_number [(ngModel)] = "business.business_gst_number" />
      </div>
      <div *ngIf="angForm.controls['business_gst_number'].invalid && (angForm.controls['business_gst_number'].dirty || angForm.controls['business_gst_number'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['business_gst_number'].errors.required">
          Business GST Number is required.
        </div>
      </div>
      <div class="form-group">
        <button (click)="updateBusiness(person_name.value, business_name.value, business_gst_number.value)"
        [disabled]="angForm.invalid" 
        class="btn btn-primary">Update Business</button>
      </div>
    </form>
  </div>
</div>

ファイルを保存し、リストページに移動し、編集ボタンをクリックして、データベースから入力されたフォームを確認します。

次のような警告も表示されます。このデモチュートリアルは無視してください。

forms.js:
1193formControlNameと同じフォームフィールドでngModelを使用しているようです。
リアクティブフォームディレクティブでのngModel入力プロパティとngModelChangeイベントの使用のサポートは
、Angular v6で非推奨になり、Angularv7で削除され
ました。

次に、データを更新します。 business.service.ts ファイル内に、データを更新する関数を記述する必要があります。

// business.service.ts

updateBusiness(person_name, business_name, business_gst_number, id) {

    const obj = {
        person_name: person_name,
        business_name: business_name,
        business_gst_number: business_gst_number
      };
    this
      .http
      .post(`${this.uri}/update/${id}`, obj)
      .subscribe(res => console.log('Done'));
  }

では、  gst-edit.component.ts ファイル内にupdateBusiness() 関数を記述します。

// gst-edit.component.ts

updateBusiness(person_name, business_name, business_gst_number) {
   this.route.params.subscribe(params => {
      this.bs.updateBusiness(person_name, business_name, business_gst_number, params['id']);
      this.router.navigate(['business']);
});

ファイルを保存すると、データを更新できるようになります。

17:データを削除します。

したがって、コンソールでエラーが見つからない場合は、データを正常に更新できます。

API呼び出しを行うための編集 および 更新サービス をすでに作成しました。したがって、これまで、このAngular CRUDの例は、作成、読み取り、更新 が完了してい ます。次に、 Deleteを見てください 。

 gst-get.component.html ファイル内の削除ボタンでクリックイベントを定義する必要があります。

<tr *ngFor="let business of businesses">
          <td>{{ business.person_name }}</td>
          <td>{{ business.business_name }}</td>
          <td>{{ business.business_gst_number }}</td>
          <td><a [routerLink]="['edit', business._id]" class="btn btn-primary">Edit</a></td>
          <td><a (click) = "deleteBusiness(business._id)" class="btn btn-danger">Delete</a></td>
</tr>

ここで、  deleteBusiness関数 をgst-get.component.ts ファイル内に 記述します。

// gst-get.component.ts

deleteBusiness(id) {
    this.bs.deleteBusiness(id).subscribe(res => {
      console.log('Deleted');
    });
  }

最後に、 business.service.ts ファイル内にdeleteBusiness() 関数を作成します。

// business.service.ts

deleteBusiness(id) {
    return this
              .http
              .get(`${this.uri}/delete/${id}`);
  }

最後に、削除機能を完了しました。

したがって、このチュートリアルでは、AngularのCRUD機能を完了しました。

Construire une application Web Crud avec Angular | Angulaire 13 CRUD

Angular CRUD désigne une application consistant à créer, lire, mettre à jour et supprimer des fonctionnalités de données. Il s'agit du guide complet sur la création d'applications Web CRUD (créer, lire, mettre à jour, supprimer) à l'aide du nouveau cadre angulaire. L'Angular vient de sortir, et il est livré avec quelques nouvelles fonctionnalités et améliorations.

Tout d'abord, nous installerons Angular en utilisant Angular CLI, puis nous continuerons à développer le frontend et le backend.

1 : Installez Angular et d'autres dépendances.

Si vous avez une ancienne version de @angular/cli, vous pouvez exécuter la commande suivante pour installer les dernières versions.

npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli

Si vous rencontrez des problèmes, veuillez consulter mon How To Update Angular CLI To Version 7Cela vous aidera à mettre à jour votre Angular CLI et vous créerez un tout nouveau projet Angular seven.

Bon, maintenant, si vous tapez la commande suivante, vous pouvez voir que nous avons mis à jour Angular CLI.

Exemple CRUD angulaire 7 |  MEAN Stack Tutoriel

Maintenant, vous allez créer un nouveau projet Angular en utilisant la commande suivante.

ng new angular7crud
cd angular7crud

MEAN Stack CRUD Exemple

Après avoir pénétré dans le dossier du projet, ouvrez le projet dans Visual Studio Code à l'aide de la commande suivante. Si vous ne l'utilisez pas, commencez à l'utiliser. C'est le meilleur éditeur pour le développement Javascript .

code .

Au moment de l'installation, nous avons activé le routage pour notre application. C'est nouveau dans Angular  car il nous invitera lors de l'installation du passe-partout angulaire. Vous pouvez vérifier le fichier appelé fichier app-routing.module.ts  dans le répertoire src >> app .

Ensuite, installez le framework CSS Bootstrap 4 à l'aide de la commande suivante.

npm install bootstrap --save

Maintenant, ajoutez-le dans le  fichier angular.json  .

"styles": [
   "src/styles.css",
   "./node_modules/bootstrap/dist/css/bootstrap.min.css"
 ],

Nous pouvons donc maintenant utiliser les classes Bootstrap 4 dans notre projet. 

Démarrez le serveur de développement angulaire à l'aide de la commande suivante.

ng serve -o

 

Procédure pas à pas angulaire 7

Description du projet

Nous créerons un projet dans lequel les utilisateurs pourront entrer leur nom d'utilisateur  , leur nom commercial  et leur numéro de TPS à partir du formulaire et le soumettre. Si les valeurs sont incorrectes, elles seront validées à l'interface et le formulaire ne sera pas soumis. D'autre part, si toutes les valeurs semblent parfaites, nous enverrons le formulaire à l' API backend , en stockant les valeurs dans la base de données MongoDB .

Alors maintenant, nous allons créer des composants angulaires pour faire le travail.

2 : Générer des composants angulaires

Tapez la commande suivante pour générer des composants angulaires . Nous allons effectuer des opérations de création, de lecture, de mise à jour. Nous allons donc créer trois composants.

ng g c gst-add --spec=false
ng g c gst-get --spec=false
ng g c gst-edit --spec=false

Tutoriel CRUD angulaire

Les trois composants sont automatiquement enregistrés dans un fichier app.module.ts  . Nous devons configurer le routage des composants angulaires dans un fichier app-routing.module.ts  .

// app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { GstAddComponent } from './gst-add/gst-add.component';
import { GstEditComponent } from './gst-edit/gst-edit.component';
import { GstGetComponent } from './gst-get/gst-get.component';

const routes: Routes = [
  {
    path: 'business/create',
    component: GstAddComponent
  },
  {
    path: 'business/edit/:id',
    component: GstEditComponent
  },
  {
    path: 'business',
    component: GstGetComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

export class AppRoutingModule { }

Maintenant, vous pouvez voir à l'intérieur du  fichier app.component.html  que la directive <router-outlet>  est là. Cette directive nous aide à rendre les différents composants en fonction de l'URI de la route.

3 : Créer une navigation angulaire

Écrivez le code suivant dans le  fichier app.component.html  .

<nav class="navbar navbar-expand-sm bg-light">
  <div class="container-fluid">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a routerLink="business/create" class="nav-link" routerLinkActive="active">
          Create Business
        </a>
      </li>
      <li class="nav-item">
        <a routerLink="business" class="nav-link" routerLinkActive="active">
          Business
        </a>
      </li> 
    </ul>
  </div>
</nav>

<div class="container">
  <router-outlet></router-outlet>
</div>

Enregistrez le fichier et accédez au navigateur et cliquez sur deux liens. Vous pouvez voir que nous pouvons voir les différents composants en fonction de la navigation.

4 : Installez l'indicateur de progression du routage angulaire.

Tapez la commande suivante pour installer la  bibliothèque ng2-slim-loading-bar .

npm install ng2-slim-loading-bar --save

Donc, si vous installez des packages tiers en ce moment, il n'est pas compatible avec Angular . Pour combler le fossé entre  les packages angulaires  et tiers, nous devons installer la bibliothèque suivante. C'est ça.

npm install rxjs-compat --save

Maintenant, importez le  SlimLoadingBarModule  dans le  fichier app.module.ts  .

// app.module.ts

import { SlimLoadingBarModule } from 'ng2-slim-loading-bar';

imports: [
    ...
    SlimLoadingBarModule
],

L'étape suivante consiste à inclure le style avec la bibliothèque dans le fichier src >> styles.css  .

@import "../node_modules/ng2-slim-loading-bar/style.css";

5 : Ajout d'événements de routeur.

Angular RouterModule nous donne les modules d'événements suivants.

  1. NavigationDémarrer
  2. NavigationFin
  3. Erreur de navigation
  4. NavigationAnnuler
  5. Routeur
  6. Événement

Maintenant, écrivez le code suivant dans le  fichier app.component.ts  .

// app.component.ts

import { Component } from '@angular/core';
import {SlimLoadingBarService} from 'ng2-slim-loading-bar';
import { NavigationCancel,
        Event,
        NavigationEnd,
        NavigationError,
        NavigationStart,
        Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular7crud';
  constructor(private _loadingBar: SlimLoadingBarService, private _router: Router) {
    this._router.events.subscribe((event: Event) => {
      this.navigationInterceptor(event);
    });
  }
  private navigationInterceptor(event: Event): void {
    if (event instanceof NavigationStart) {
      this._loadingBar.start();
    }
    if (event instanceof NavigationEnd) {
      this._loadingBar.complete();
    }
    if (event instanceof NavigationCancel) {
      this._loadingBar.stop();
    }
    if (event instanceof NavigationError) {
      this._loadingBar.stop();
    }
  }
}

Il intercepte l'événement de routage et ajoute le composant de barre de chargement à chaque route afin que nous puissions voir l'indication de routage chaque fois que nous modifions les routes.

Le dernier changement pour afficher l'indicateur de routage consiste à ajouter la directive ng2-slim-loading-bar dans le  fichier app.component.html  en haut de la page.

<ng2-slim-loading-bar color="blue"></ng2-slim-loading-bar>

<nav class="navbar navbar-expand-sm bg-light">
  <div class="container-fluid">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a routerLink="business/create" class="nav-link" routerLinkActive="active">
          Create Business
        </a>
      </li>
      <li class="nav-item">
        <a routerLink="business" class="nav-link" routerLinkActive="active">
          Business
        </a>
      </li> 
    </ul>
  </div>
</nav>

<div class="container">
  <router-outlet></router-outlet>
</div>

Enregistrez le fichier et accédez au terminal pour voir s'il y a une erreur et sinon, accédez au navigateur et modifiez les itinéraires, et vous pouvez voir que maintenant nous pouvons voir l'indicateur de routage.

6 : Ajouter un formulaire Bootstrap

Dans le  fichier gst-add.component.html  , ajoutez le  formulaire bootstrap 4 suivant .

<div class="card">
  <div class="card-body">
    <form>
      <div class="form-group">
        <label class="col-md-4">Person Name</label>
        <input type="text" class="form-control" />
      </div>
      <div class="form-group">
        <label class="col-md-4">Business Name </label>
        <input type="text" class="form-control" />
      </div>
      <div class="form-group">
        <label class="col-md-4">Business GST Number </label>
        <input type="text" class="form-control" />
      </div>
      <div class="form-group">
        <button type="submit" class="btn btn-primary">Add Business</button>
      </div>
    </form>
  </div>
</div>

Démo angulaire 7 CRUD

7 : Ajouter une validation de forme angulaire

Nous utiliserons ReactiveFormsModule . Donc, si vous êtes nouveau dans la validation de la forme angulaire , veuillez consulter mon article sur la validation de la forme angulaire  sur ce blog.

Maintenant, importez le  ReactiveFormsModule  dans le  fichier app.module.ts  .

// app.module.ts

import { ReactiveFormsModule } from '@angular/forms';

imports: [
    ...
    ReactiveFormsModule
],

Maintenant, nous devons écrire le code du  fichier app.component.ts  . N'oubliez pas qu'il ne s'agit pas d'un formulaire basé sur un modèle. Nous allons donc modifier le code à l'intérieur du fichier app.component.ts  .

Tout d'abord, nous importons les  modules FormGroup, FormBuilder, Validators  de  @angular/forms .

Créez également un constructeur et instanciez le  FormBuilder .

Écrivez donc le code suivant dans le  fichier gst-add.component.ts  .

// gst-add.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';

@Component({
  selector: 'app-gst-add',
  templateUrl: './gst-add.component.html',
  styleUrls: ['./gst-add.component.css']
})
export class GstAddComponent implements OnInit {

  angForm: FormGroup;
  constructor(private fb: FormBuilder) {
    this.createForm();
  }

  createForm() {
    this.angForm = this.fb.group({
      person_name: ['', Validators.required ],
      business_name: ['', Validators.required ],
      business_gst_number: ['', Validators.required ]
    });
  }

  ngOnInit() {
  }

}

Nous avons utilisé le générateur de formulaires pour gérer toute la validation. Donc, dans ce constructeur, nous créons un formulaire avec les règles de validation. Dans notre exemple, il y a trois champs. Si le texte d'entrée est vide, cela donnera une erreur et nous devons l'afficher.

Maintenant, écrivez le code suivant dans le  fichier gst-add.component.html  .

<div class="card">
  <div class="card-body">
    <form [formGroup]="angForm" novalidate>
      <div class="form-group">
        <label class="col-md-4">Person Name</label>
        <input type="text" class="form-control" formControlName="person_name" #person_name />
      </div>
      <div *ngIf="angForm.controls['person_name'].invalid && (angForm.controls['person_name'].dirty || angForm.controls['person_name'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['person_name'].errors.required">
          Person Name is required.
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-4">Business Name </label>
        <input type="text" class="form-control" formControlName="business_name" #business_name />
      </div>
      <div *ngIf="angForm.controls['business_name'].invalid && (angForm.controls['business_name'].dirty || angForm.controls['business_name'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['business_name'].errors.required">
          Person Business is required.
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-4">Business GST Number </label>
        <input type="text" class="form-control" formControlName="business_gst_number" #business_gst_number />
      </div>
      <div *ngIf="angForm.controls['business_gst_number'].invalid && (angForm.controls['business_gst_number'].dirty || angForm.controls['business_gst_number'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['business_gst_number'].errors.required">
          Business GST Number is required.
        </div>
      </div>
      <div class="form-group">
        <button type="submit" 
        [disabled]="angForm.pristine || angForm.invalid" 
        class="btn btn-primary">Add Business</button>
      </div>
    </form>
  </div>
</div>

Enregistrez le fichier et accédez au navigateur, et vous pouvez voir si vous ne mettez aucune valeur dans la zone de saisie, vous verrez les erreurs.

Exemple de validation de formulaire angulaire 7

8 : Configurer le HttpClientModule

Importez le  HttpClientModule  dans le  fichier app.module.ts  .

// app.module.ts

import { HttpClientModule } from '@angular/common/http';

imports: [
   ...
    HttpClientModule
 ],

9 : Créer un modèle.

Dans le  dossier src >> app  , créez un fichier appelé  Business.ts  et ajoutez le code suivant.

// Business.ts

export default class Business {
  person_name: String;
  business_name: String;
  business_gst_number: Number;
}

10 : Créez un fichier de service angulaire.

Tapez la commande suivante pour générer le fichier de service.

ng g service business --spec=false

Ainsi, votre fichier principal  business.service.ts  ressemble à ceci.

// business.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class BusinessService {

  constructor() { }
}

Maintenant, importez le  fichier business.service.ts  dans le  fichier app.module.ts  .

// app.module.ts

import { BusinessService } from './business.service';

providers: [ BusinessService ],

11 : Soumettre les données au serveur de nœud

Nous devons écrire le code qui enverra la requête HTTP POST avec les données au serveur Node.js et enregistrer les données dans la base de données MongoDB .

Écrivez le code suivant dans le  fichier business.service.ts  .

// business.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class BusinessService {

  uri = 'http://localhost:4000/business';

  constructor(private http: HttpClient) { }

  addBusiness(person_name, business_name, business_gst_number) {
    const obj = {
      person_name: person_name,
      business_name: business_name,
      business_gst_number: business_gst_number
    };
    console.log(obj);
    this.http.post(`${this.uri}/add`, obj)
        .subscribe(res => console.log('Done'));
  }
}

Nous avons défini l'URL de notre API backend, mais nous n'avons pas encore créé de backend, mais nous le ferons en quelques étapes.

Nous devons ajouter l'événement de clic au bouton Ajouter une entreprise. Ajoutez donc le code suivant dans le fichier gst-add.component.html  .

<div class="form-group">
    <button (click)="addBusiness(person_name.value, business_name.value, business_gst_number.value)"
        [disabled]="angForm.pristine || angForm.invalid" 
        class="btn btn-primary">
        Add Business
     </button>
</div>

Ainsi, lorsqu'il n'y a pas d'erreurs, nous pouvons soumettre le formulaire et il appellera la  fonction addBusiness  du composant . À partir de là, nous appellerons le service angulaire, et le service enverra la requête HTTP Post au serveur Node.js.

Maintenant, ajoutez la  fonction  addBusiness  dans le fichier gst-add.component.ts  . Écrivez donc le code suivant dans  le fichier gst-add.component.ts  .

// gst-add.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';
import { BusinessService } from '../business.service';

@Component({
  selector: 'app-gst-add',
  templateUrl: './gst-add.component.html',
  styleUrls: ['./gst-add.component.css']
})
export class GstAddComponent implements OnInit {

  angForm: FormGroup;
  constructor(private fb: FormBuilder, private bs: BusinessService) {
    this.createForm();
  }

  createForm() {
    this.angForm = this.fb.group({
      person_name: ['', Validators.required ],
      business_name: ['', Validators.required ],
      business_gst_number: ['', Validators.required ]
    });
  }

  addBusiness(person_name, busines_name, business_gst_number) {
    this.bs.addBusiness(person_name, busines_name, business_gst_number);
  }

  ngOnInit() {
  }

}

Ici, nous avons défini la fonction et également importé le  fichier business.service.ts  . Ensuite, instanciez l'objet dans le constructeur et appelez la fonction du fichier businsess.service.ts .

Nous avons déjà codé la  fonction  addBusiness  dans le fichier business.service.ts  . Maintenant, nous devons configurer l'API backend.

12 : Créer une API back-end Node.js

Dans le dossier racine angulaire, créez un dossier appelé api et accédez à ce dossier. N'oubliez pas qu'il s'agira d'un projet complètement distinct d'Angular. Ainsi, ses node_modules sont différents d'un Angular .

Ouvrez le terminal dans le  dossier api  et tapez la commande suivante.

npm init -y

Installez les modules spécifiques aux nœuds suivants.

npm install --save express body-parser cors mongoose

Je ne redémarre pas le serveur de nœud à chaque fois ; Je change le fichier. J'installe donc le serveur nodemon. Ce qu'il fait, c'est que lorsque je modifie le fichier server.js  , il redémarre  automatiquement le serveur node.js. 

npm install nodemon --save-dev

Maintenant, dans le  dossier api  , créez un fichier appelé  fichier server.js  .

// server.js

const express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    mongoose = require('mongoose');

    const app = express();
    let port = process.env.PORT || 4000;

    const server = app.listen(function(){
        console.log('Listening on port ' + port);
    });

La prochaine chose est de connecter la base de données MongoDB avec notre application node.js.

Si vous n'avez pas installé la base de données MongoDB, installez-la et démarrez le serveur mongodb.

Tapez la commande suivante pour démarrer le   serveur MongoDB .

mongod

Donc, maintenant, je me suis connecté à la base de données.

Créez un fichier appelé  DB.js  dans  le dossier du projet racine api  . Ensuite, écrivez le code suivant dans le fichier DB.js. 

// DB.js

module.exports = {
    DB: 'mongodb://localhost:27017/ng7crud'
 };

Importez ce  fichier DB.js  dans notre  fichier server.js et utilisez la  bibliothèque mongoose  pour configurer la  connexion à la base de données  avec  MongoDB . Nous pouvons également utiliser Mongoose pour enregistrer les données dans la base de données à l'aide de Mongoose ORM.

Écrivez le code suivant dans le fichier server.js  pour connecter notre  application  MongoDB  au serveur Node.js. 

// server.js

const express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    mongoose = require('mongoose'),
    config = require('./DB');

    mongoose.Promise = global.Promise;
    mongoose.connect(config.DB, { useNewUrlParser: true }).then(
      () => {console.log('Database is connected') },
      err => { console.log('Can not connect to the database'+ err)}
    );

    const app = express();
    app.use(bodyParser.json());
    app.use(cors());
    const port = process.env.PORT || 4000;

    const server = app.listen(port, function(){
     console.log('Listening on port ' + port);
    });

Enregistrez le fichier et accédez au terminal et démarrez le serveur de nœud.

nodemon server

Donc, en ce moment, vous avez trois serveurs en cours d'exécution.

  1. Serveur de développement angulaire
  2. Serveur Nodémon
  3. Serveur MongoDB

N'oubliez pas que les trois serveurs fonctionnent correctement sans aucune erreur ; sinon, notre application ne fonctionnera pas.

Étape 13 : Créer un modèle et des itinéraires pour notre application.

Nous devons créer deux dossiers dans le dossier racine de l' api appelés routes et models .

Dans le dossier des modèles  , créez un modèle appelé  Business.js.

// Business.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Define collection and schema for Business
let Business = new Schema({
  person_name: {
    type: String
  },
  business_name: {
    type: String
  },
  business_gst_number: {
    type: Number
  }
},{
    collection: 'business'
});

module.exports = mongoose.model('Business', Business);

Nous avons donc défini notre schéma pour la collection métier. Nous avons trois champs appelés  person_name, business_name, business_gst_number.

Dans le  dossier routes  , créez un fichier appelé business.route.js.

Écrivez le code CRUD dans le  fichier business.route.js  .

// business.route.js

const express = require('express');
const app = express();
const businessRoutes = express.Router();

// Require Business model in our routes module
let Business = require('../models/Business');

// Defined store route
businessRoutes.route('/add').post(function (req, res) {
  let business = new Business(req.body);
  business.save()
    .then(business => {
      res.status(200).json({'business': 'business in added successfully'});
    })
    .catch(err => {
    res.status(400).send("unable to save to database");
    });
});

// Defined get data(index or listing) route
businessRoutes.route('/').get(function (req, res) {
    Business.find(function (err, businesses){
    if(err){
      console.log(err);
    }
    else {
      res.json(businesses);
    }
  });
});

// Defined edit route
businessRoutes.route('/edit/:id').get(function (req, res) {
  let id = req.params.id;
  Business.findById(id, function (err, business){
      res.json(business);
  });
});

//  Defined update route
businessRoutes.route('/update/:id').post(function (req, res) {
    Business.findById(req.params.id, function(err, next, business) {
    if (!business)
      return next(new Error('Could not load Document'));
    else {
        business.person_name = req.body.person_name;
        business.business_name = req.body.business_name;
        business.business_gst_number = req.body.business_gst_number;

        business.save().then(business => {
          res.json('Update complete');
      })
      .catch(err => {
            res.status(400).send("unable to update the database");
      });
    }
  });
});

// Defined delete | remove | destroy route
businessRoutes.route('/delete/:id').get(function (req, res) {
    Business.findByIdAndRemove({_id: req.params.id}, function(err, business){
        if(err) res.json(err);
        else res.json('Successfully removed');
    });
});

module.exports = businessRoutes;

Nous avons utilisé le modèle mangouste pour enregistrer, mettre à jour et supprimer la base de données. Mongoose est un ORM utilisé dans la base de données MongoDB . Toutes les opérations CRUD sont configurées sur le fichier de route ; nous devons les importer dans le fichier server.js  .

Ainsi, notre  fichier server.js  final ressemble à ceci.

// server.js

const express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    mongoose = require('mongoose'),
    config = require('./DB');

const businessRoute = require('./routes/business.route');
mongoose.Promise = global.Promise;
mongoose.connect(config.DB, { useNewUrlParser: true }).then(
  () => {console.log('Database is connected') },
  err => { console.log('Can not connect to the database'+ err)}
);

const app = express();
app.use(bodyParser.json());
app.use(cors());
app.use('/business', businessRoute);
const port = process.env.PORT || 4000;

const server = app.listen(port, function(){
  console.log('Listening on port ' + port);
});

Étape 14 : Tester la fonctionnalité de données du magasin

Si tous les serveurs sont opérationnels, vous pouvez accéder au navigateur, remplir les données du formulaire et ajouter l'entreprise. Vous pouvez voir quelque chose comme ça sur votre écran si vous réussissez.

Maintenant, nous pouvons vérifier la base de données en utilisant les commandes suivantes.

Tout d'abord, ouvrez le shell mongo sur le 4ème onglet car les trois autres onglets sont occupés pour le moment.

mongo

Ici, nous pouvons voir que les valeurs sont stockées dans la base de données MongoDB. Oui !! Nous avons réussi.

Maintenant, les opérations restantes sont Lire, Mettre à jour et Supprimer.

15 : Afficher les données sur le frontend

Dans le fichier gst-get.component.html  , écrivez le code suivant.

<table class="table table-hover">
  <thead>
  <tr>
      <td>Person Name</td>
      <td>Business Name</td>
      <td>GST Number</td>
      <td colspan="2">Actions</td>
  </tr>
  </thead>

  <tbody>
      <tr *ngFor="let business of businesses">
          <td>{{ business.person_name }}</td>
          <td>{{ business.business_name }}</td>
          <td>{{ business.business_gst_number }}</td>
          <td><a [routerLink]="['/edit', business._id]" class="btn btn-primary">Edit</a></td>
          <td><a [routerLink]="" class="btn btn-danger">Delete</a></td>
      </tr>
  </tbody>
</table>

Maintenant, dans le  fichier business.service.ts  , nous devons écrire la fonction récupérant les données commerciales de la  base de données MongoDB et les affichant dans l' application Angular .

// business.service.ts

getBusinesses() {
    return this
           .http
           .get(`${this.uri}`);
  }

Nous devons inclure ce fichier business.service.ts  et ce fichier Business.ts  dans le fichier  gst-get.component.ts  .

Écrivez le code suivant dans le  fichier gst-get.component.ts  .

// gst-get.component.ts

import { Component, OnInit } from '@angular/core';
import Business from '../Business';
import { BusinessService } from '../business.service';

@Component({
  selector: 'app-gst-get',
  templateUrl: './gst-get.component.html',
  styleUrls: ['./gst-get.component.css']
})
export class GstGetComponent implements OnInit {

  businesses: Business[];

  constructor(private bs: BusinessService) { }

  ngOnInit() {
    this.bs
      .getBusinesses()
      .subscribe((data: Business[]) => {
        this.businesses = data;
    });
  }
}

Enregistrez le fichier, accédez au navigateur et passez à cette URL :  http://localhost:4200/business. Vous pouvez voir la liste des entreprises.

16 : Modifier et mettre à jour les données

D'accord, d'abord, nous devons récupérer les données de la base de données MongoDB en utilisant _id wise et afficher ces données dans le fichier gst-edit.component.html  .

Alors d'abord, écrivez le code suivant dans le  fichier gst-edit.component.ts  .

// gst-edit.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';
import { BusinessService } from '../business.service';

@Component({
  selector: 'app-gst-edit',
  templateUrl: './gst-edit.component.html',
  styleUrls: ['./gst-edit.component.css']
})
export class GstEditComponent implements OnInit {

  business: any = {};
  angForm: FormGroup;

  constructor(private route: ActivatedRoute,
    private router: Router,
    private bs: BusinessService,
    private fb: FormBuilder) {
      this.createForm();
 }

  createForm() {
    this.angForm = this.fb.group({
        person_name: ['', Validators.required ],
        business_name: ['', Validators.required ],
        business_gst_number: ['', Validators.required ]
      });
    }


  ngOnInit() {
    this.route.params.subscribe(params => {
        this.bs.editBusiness(params['id']).subscribe(res => {
          this.business = res;
      });
    });
  }
}

Ici, lorsque le  gst-edit component.ts est  rendu, il appelle la  méthode ngOnInit  et envoie une requête HTTP au serveur de nœud et récupère les données d'un _id à afficher dans le  fichier gst-edit.component.html  .

Maintenant, dans le  fichier business.service.ts  , nous devons coder la  fonction editBusiness  pour envoyer une requête HTTP.

// business.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class BusinessService {

  uri = 'http://localhost:4000/business';

  constructor(private http: HttpClient) { }

  addBusiness(person_name, business_name, business_gst_number) {
    const obj = {
      person_name: person_name,
      business_name: business_name,
      business_gst_number: business_gst_number
    };
    this.http.post(`${this.uri}/add`, obj)
        .subscribe(res => console.log('Done'));
  }

  getBusinesses() {
    return this
           .http
           .get(`${this.uri}`);
  }

  editBusiness(id) {
    return this
            .http
            .get(`${this.uri}/edit/${id}`);
    }
}

Enfin, nous devons écrire le formulaire dans le fichier gst-edit.component.html  .

<div class="card">
  <div class="card-body">
    <form [formGroup]="angForm" novalidate>
      <div class="form-group">
        <label class="col-md-4">Person Name</label>
        <input type="text" class="form-control" formControlName="person_name" #person_name [(ngModel)] = "business.person_name" />
      </div>
      <div *ngIf="angForm.controls['person_name'].invalid && (angForm.controls['person_name'].dirty || angForm.controls['person_name'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['person_name'].errors.required">
          Person Name is required.
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-4">Business Name </label>
        <input type="text" class="form-control" formControlName="business_name" #business_name [(ngModel)] = "business.business_name" />
      </div>
      <div *ngIf="angForm.controls['business_name'].invalid && (angForm.controls['business_name'].dirty || angForm.controls['business_name'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['business_name'].errors.required">
          Person Business is required.
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-4">Business GST Number </label>
        <input type="text" class="form-control" formControlName="business_gst_number" #business_gst_number [(ngModel)] = "business.business_gst_number" />
      </div>
      <div *ngIf="angForm.controls['business_gst_number'].invalid && (angForm.controls['business_gst_number'].dirty || angForm.controls['business_gst_number'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['business_gst_number'].errors.required">
          Business GST Number is required.
        </div>
      </div>
      <div class="form-group">
        <button (click)="updateBusiness(person_name.value, business_name.value, business_gst_number.value)"
        [disabled]="angForm.invalid" 
        class="btn btn-primary">Update Business</button>
      </div>
    </form>
  </div>
</div>

Enregistrez le fichier, accédez à la page de liste, cliquez sur le bouton Modifier et consultez le formulaire rempli à partir de la base de données.

Vous pouvez également voir l'avertissement comme suit. Ignorez ce tutoriel de démonstration.

forms.js:1193
Il semble que vous utilisiez ngModel sur le même champ de formulaire que formControlName.
La prise en charge de l'utilisation de la propriété d'entrée ngModel et de l'événement ngModelChange avec
des directives de formulaire réactives a été obsolète dans Angular v6 et supprimée
dans Angular v7.

Maintenant, mettez à jour les données. Dans le fichier  business.service.ts  , nous devons écrire la fonction qui met à jour les données.

// business.service.ts

updateBusiness(person_name, business_name, business_gst_number, id) {

    const obj = {
        person_name: person_name,
        business_name: business_name,
        business_gst_number: business_gst_number
      };
    this
      .http
      .post(`${this.uri}/update/${id}`, obj)
      .subscribe(res => console.log('Done'));
  }

Bon, écrivez maintenant la  fonction updateBusiness()  dans le fichier gst-edit.component.ts  .

// gst-edit.component.ts

updateBusiness(person_name, business_name, business_gst_number) {
   this.route.params.subscribe(params => {
      this.bs.updateBusiness(person_name, business_name, business_gst_number, params['id']);
      this.router.navigate(['business']);
});

Enregistrez le fichier et vous pourrez mettre à jour les données.

17 : Supprimer les données.

Ainsi, si vous ne trouvez aucune erreur sur la console, vous pouvez mettre à jour les données avec succès.

J'ai déjà écrit un service d' édition  et  de mise à jour  pour effectuer des appels d'API. Donc jusqu'à présent, Créer, Lire, Mettre à jour  est complet de cet  exemple CRUD angulaire . Maintenant, jetez un œil à  Supprimer .

Nous devons définir l'événement de clic sur le bouton de suppression dans le fichier  gst-get.component.html  .

<tr *ngFor="let business of businesses">
          <td>{{ business.person_name }}</td>
          <td>{{ business.business_name }}</td>
          <td>{{ business.business_gst_number }}</td>
          <td><a [routerLink]="['edit', business._id]" class="btn btn-primary">Edit</a></td>
          <td><a (click) = "deleteBusiness(business._id)" class="btn btn-danger">Delete</a></td>
</tr>

Maintenant, écrivez la  fonction deleteBusiness  dans le  fichier gst-get.component.ts  .

// gst-get.component.ts

deleteBusiness(id) {
    this.bs.deleteBusiness(id).subscribe(res => {
      console.log('Deleted');
    });
  }

Enfin, créez la fonction deleteBusiness()  dans le fichier business.service.ts  .

// business.service.ts

deleteBusiness(id) {
    return this
              .http
              .get(`${this.uri}/delete/${id}`);
  }

Enfin, j'ai terminé la fonctionnalité de suppression.

Ainsi, dans ce didacticiel, nous avons terminé la fonctionnalité CRUD dans Angular.