Dwayne  Smith

Dwayne Smith

1652774126

What is Business Accounting and Taxation?

Overview

Business Accounting Taxation Courses For Everyone | ICA Edu Skills

Business accounting is the process of using non-financial information to measure, analyze, and communicate financial information to help a company meet internal needs. Taxation, on the other hand, is the process of collecting money from citizens and governments. In short, business accounting helps companies meet their internal goals and objectives. Both are important and require advanced education. Read on to learn more. The next time you hear someone ask, "What is business accounting and taxation?", consider the answer to these questions.

GAAP accounting

To understand the requirements of GAAP accounting, it is helpful to learn about the ten principles of accounting. These principles govern the preparation of financial statements, and should be used to prepare the accounting records of business enterprises. They must also measure revenue and expenses according to GAAP standards. Financial statements are generally comprised of an income statement, balance sheet, cash flow statement, and statement of shareholder's equity. The notes in the financial statements should explain any information they may contain.

Business owners who don't understand GAAP should speak with their accountants about it. GAAP accounting rules ensure that businesses present financial statements in a consistent manner, making them more readable and appealing to investors. Small business owners should take advantage of the standards of financial reporting to make sure they receive the support of financial institutions. By complying with GAAP accounting principles, they will be well prepared to work with their accountants. And, as the business owner, you should know what these rules are so that you can communicate with them effectively.

Article Source : Business Assignment Help Experts

Private companies that issue financial statements may also consider GAAP standards for their accounting. Although private companies are not required to follow GAAP, they may want to do so to better communicate with other stakeholders and for comparison. Even if GAAP is not required, it is a good idea to get started early. The principles of GAAP accounting are based on industry standards, which are not subject to annual tax changes. If your company is new to accounting, you may want to start using GAAP standards early.

While the complexities of business operations required the development of standardized accounting practices, the importance of financial accounting cannot be overemphasized. With financial accounting as the backbone of any business, the need for standardization was necessary. In the U.S., GAAPs were introduced by the Financial Accounting Standard Board (FASB). Similarly, the sixteenth Amendment of the United States Constitution initiated a revenue collection agency in 1894. This agency is now known as the Internal Revenue Service.

Article Source : Business Assignment Help Experts

Double-entry bookkeeping

Double-entry bookkeeping is a method of accounting that records every financial transaction in two parts: a credit and a debit. In other words, every time money enters a business account, it must be credited and debited. As an example, an owner of a company that sells office supplies would have to credit $5,000 and debit $500 in the debit section of the ledger. In this manner, the owner can track every transaction in detail and see if the amount of cash is correct.

The principle of double-entry bookkeeping is to record each transaction in two separate accounts, the general ledger and the account for the equipment he purchased. Complex transactions may require more than two entries. These two separate accounts are used to create the balance sheet and income statement, which reflect the profitability of the business. Ultimately, a person's expenses must be subtracted from his or her revenue to determine the business's profitability.

In a double-entry system, debits increase an account's value and credits decrease it. This system makes it easy for people to understand the books, and it makes it easier to spot errors or discrepancies. It is important to note that a public company must use double-entry bookkeeping to comply with the requirements of the Financial Accounting Standards Board, a nongovernmental body that sets accounting standards.

The fundamentals of double-entry bookkeeping are based on an equation, with debits and credits represented as opposing entries. Every business transaction affects the value of the company's assets, liabilities, and equities, or a combination of these accounts. The balance sheet reflects the value of each of these three elements. A business's income statement is also made up of both debits and credits.

When double-entry bookkeeping is used, a company can view every aspect of its finances and financial health. The financial statements created from these reports will show whether a certain part of the business is profitable or not, and allow them to make informed financial decisions. Ultimately, double-entry bookkeeping will give a business an edge over its competitors. But if you're the sole owner of a business, double-entry bookkeeping is the way to go.

Article Source : Business Assignment Help Experts

Tax accounting

The primary difference between tax accounting and general accounting is that tax accounting is aimed at minimizing the business's tax burden. While general accounting tracks all of a company's funds, including personal expenses, tax accounting is focused on keeping track of the organization's income. Keeping both sets of books of accounts increases the costs of compliance and administration. However, these two types of accounting are not mutually exclusive. This article will discuss both of these types of accounting and explain the differences between them.

Accounts receivable and accounts payable are two forms of business accounting. In general, accounts receivable are formed from outstanding invoices or advances, and are considered bad when they are not paid by the time the contract expires. Bad accounts receivable are also known as hopeless debts and are included in the allowance for bad debts reserve. Accounts receivable is a component of both tax accounting and business accounting.

Tax accounting is similar to financial analysis. While financial analysts study the trends in the larger economy, tax accountants analyze the details of individual transactions. In addition, they can make recommendations for tax returns and calculate an individual's income tax. Both of these areas of accounting are regulated by the Internal Revenue Service (IRS) and adhere to its rules and regulations. It's not difficult to see the difference, but it's essential to know which one you need to pursue.

Tax accounting differs from GAAP in one important way. Generally accepted accounting principles (GAAP) are compulsory for public companies, while tax accounting is not. It has more options and can be more expensive. Knowing the differences between GAAP and tax accounting can help you determine which method would be best for your clients. The best way to choose which method is right for your business depends on the type of tax you're filing. You should always keep in mind that tax accounting is different from GAAP in many ways, including the way to allocate cost.

There are many ways to report unbilled revenue and avoid paying unnecessary taxes. For example, the meter reading and billing cycle method is widely used by utilities, such as electricity and water companies. This method is widely accepted by the Internal Revenue Service (IRS), and is also a common practice. In addition to this method, there are also cross-border transactions that fall under tax accounting. These transactions can involve the use of transfer pricing and cross-border accounting.

Article Source : Business Assignment Help Experts

Post-graduate program in business accounting and taxation

Whether you're considering a career in the accounting or taxation fields, a Post-graduate program in business and taxation can provide you with the practical training needed for success. The program emphasizes practical training and experiential learning, giving students an edge over their competition when it comes to the job market. Additionally, students can expect placement assistance and soft skills training. The program's small size ensures that each student will receive the attention they need to excel.

A business accounting and taxation post-graduate program offers students the opportunity to pursue a career in this growing field, with high salaries and good future prospects. Students will gain an in-depth understanding of taxation, auditing, finance, and indirect taxation. The average salary offered to fresh graduates is two to eight lakhs per year. The program is offered by AP Global Group's Skilling and Education vertical, and focuses on practical skills and business knowledge.

Graduates of BAT programs will learn technical accounting systems and are trained on par with MBAs and certified accountants. These programs were designed to prepare commerce graduates for a career in business accounting. Top employers of BAT students include Genpact, Bajaj, and Adobe. The course covers all aspects of accounting, including the importance of financial reporting, auditing, and payroll. They will also learn about tax deducted at source (TDS) and the components of payroll.

A Master of Science in Business Accounting and Taxation will provide the professional training needed to enter this field. This program focuses on advanced technical accounting, effective use of technology in research, and ethical responsibilities. The program prepares students to take the CPA Exam. With over 500 companies tie-ups, the program also offers hands-on training in accounting. With a practical approach, MBA students will be equipped for the challenges of a rapidly evolving profession.

The curriculum of a PGP in Business Accounting and Taxation includes an extensive study of business law and ethics, as well as accounting principles and procedures. Graduates can also choose to work in the accounting field, or become an accountant or a financial advisor. The program is offered both online and offline, and the requirements vary according to the institute. Candidates must possess a B.Com or B.B.I. or BAF in order to be accepted into the program.

What is GEEK

Buddha Community

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

Создание веб-приложения Crud с использованием Angular | Angular 13 CRUD

Angular CRUD означает приложение, состоящее из функций создания, чтения, обновления и удаления данных. Это исчерпывающее руководство по созданию веб-приложений CRUD (создание, чтение, обновление, удаление) с использованием новой Angular Framework. Только что выпущенный Angular содержит несколько новых функций и улучшений.

Сначала установим Angular с помощью Angular CLI, а потом продолжим разработку фронтенда и бэкенда.

1: Установите Angular и другие зависимости.

Если у вас более старая версия @angular/cli, вы можете запустить следующую команду, чтобы установить последние версии.

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

Если у вас возникли какие-либо проблемы, ознакомьтесь с моим Как обновить Angular CLI до версии 7Это поможет вам обновить ваш Angular CLI , и вы создадите совершенно новый проект Angular 7.

Хорошо, теперь, если вы введете следующую команду, вы увидите, что мы обновили Angular CLI.

Angular 7 Пример CRUD |  Учебное пособие по стеку MEAN

Теперь вы создадите новый проект Angular, используя следующую команду.

ng new angular7crud
cd angular7crud

Пример CRUD стека MEAN

Зайдя в папку проекта, откройте проект в Visual Studio Code с помощью следующей команды. Если вы не используете его, то начните использовать его. Это лучший редактор для разработки Javascript .

code .

Во время установки мы включили маршрутизацию для нашего приложения. Это новое в Angular  , потому что оно будет подсказывать нам при установке шаблона angular. Вы можете проверить файл с именем app-routing.module.ts  внутри каталога src >> app .

Затем установите Bootstrap 4 CSS Framework с помощью следующей команды.

npm install bootstrap --save

Теперь добавьте его в  файл angular.json  .

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

Итак, теперь мы можем использовать классы Bootstrap 4 в нашем проекте. 

Запустите сервер разработки Angular с помощью следующей команды.

ng serve -o

 

Угловой 7 прохождение

Описание Проекта

Мы создадим проект, в котором пользователи смогут ввести свое имя пользователя  , название компании  и номер GST из формы и отправить ее. Если значения неверны, они будут проверены во внешнем интерфейсе, и форма не будет отправлена. С другой стороны, если все значения кажутся идеальными, мы отправим форму на серверный API , сохранив значения в базе данных MongoDB .

Итак, теперь мы создадим несколько угловых компонентов для выполнения этой работы.

2: Создание угловых компонентов

Введите следующую команду для создания Angular Components . Мы будем выполнять операции создания, чтения, обновления. Итак, мы создадим три компонента.

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

Учебное пособие по угловому CRUD

Все три компонента автоматически регистрируются в файле app.module.ts  . Нам нужно настроить маршрутизацию компонентов angular внутри файла 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 { }

Теперь вы можете видеть внутри  файла 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>

Сохраните файл и перейдите в браузер и нажмите на две ссылки. Вы можете видеть, что мы можем видеть различные компоненты на основе навигации.

4: Установите индикатор выполнения угловой маршрутизации.

Введите следующую команду, чтобы установить  библиотеку ng2-slim-loading-bar .

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

Итак, если вы устанавливаете сторонние пакеты прямо сейчас, они несовместимы с Angular . Чтобы преодолеть разрыв между  Angular  и сторонними пакетами, нам нужно установить следующую библиотеку. Вот и все.

npm install rxjs-compat --save

Теперь импортируйте  SlimLoadingBarModule  в  файл app.module.ts  .

// 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. НавигацияНачало
  2. NavigationEnd
  3. NavigationError
  4. НавигацияОтмена
  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();
    }
  }
}

Он перехватывает событие маршрутизации и добавляет компонент панели загрузки к каждому маршруту, чтобы мы могли видеть индикацию маршрутизации каждый раз, когда меняем маршруты.

Последнее изменение для отображения индикатора маршрутизации — добавление директивы ng2-slim-loading-bar в  файл app.component.html  вверху страницы.

<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 7 Демонстрация CRUD

7: Добавить проверку угловой формы

Мы будем использовать ReactiveFormsModule . Поэтому, если вы новичок в Angular Form Validation , ознакомьтесь с моей статьей Angular Form Validation  в этом блоге.

Теперь импортируйте  ReactiveFormsModule  в  файл app.module.ts  .

// app.module.ts

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

imports: [
    ...
    ReactiveFormsModule
],

Теперь нам нужно написать код для  файла app.component.ts  . Помните, что это не шаблонная форма. Поэтому мы изменим код внутри файла app.component.ts  .

Сначала мы импортируем  модули FormGroup, FormBuilder, Validators  из  @angular/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() {
  }

}

Мы использовали конструктор форм для обработки всей проверки. Итак, в этом конструкторе мы создаем форму с правилами проверки. В нашем примере есть три поля. Если вводимый текст пустой, он выдаст ошибку, и нам нужно его отобразить.

Теперь напишите следующий код в  файле 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>

Сохраните файл и зайдите в браузер, и вы увидите, что если вы не поместите какое-либо значение в поле ввода, вы увидите ошибки.

Пример проверки формы Angular 7

8: Настройте HttpClientModule

Импортируйте  HttpClientModule  в  файл app.module.ts  .

// app.module.ts

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

imports: [
   ...
    HttpClientModule
 ],

9: Создайте модель.

В папке  приложения src >>  создайте один файл с именем  Business.ts  и добавьте следующий код.

// Business.ts

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

10: Создайте файл службы Angular.

Введите следующую команду, чтобы сгенерировать файл службы.

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: Отправить данные на сервер узла

Нам нужно написать код, который будет отправлять HTTP - запрос POST с данными на сервер 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'));
  }
}

Мы определили URL-адрес API нашего бэкэнда, но мы еще не создали никакого бэкэнда, но сделаем это за пару шагов.

Нам нужно добавить событие клика к кнопке «Добавить бизнес». Поэтому добавьте следующий код в файл 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, и служба отправит запрос HTTP Post на сервер Node.js.

Теперь добавьте  функцию addBusiness в  файл  gst-add.component.ts  . Поэтому напишите следующий код  в файле 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: Создайте серверный API Node.js

Внутри корневой папки angular создайте одну папку с именем api и войдите в эту папку. Помните, что это будет совершенно отдельный от 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  .

// 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

Итак, теперь я подключился к базе данных.

Создайте один файл с именем  DB.js  в  корневой папке проекта API  . Затем напишите следующий код в файле DB.js. 

// DB.js

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

Импортируйте этот  файл DB.js  в наш  файл server.js и используйте  библиотеку mongoose  для настройки соединения  базы данных  с  MongoDB . Мы также можем использовать Mongoose для сохранения данных в базе данных с помощью Mongoose ORM.

Напишите следующий код в файле 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

Итак, прямо сейчас у вас работают три сервера.

  1. Угловой сервер разработки
  2. нодемон сервер
  3. Сервер MongoDB

Помните, что все три сервера работают нормально, без каких-либо ошибок; иначе наше приложение не будет работать.

Шаг 13: Создайте модель и маршруты для нашего приложения.

Нам нужно создать две папки внутри корневой папки API с именами route и models .

В папке моделей  создайте одну модель с именем  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);

Итак, мы определили нашу схему для бизнес-коллекции. У нас есть три поля  с именами person_name, business_name, business_gst_number.

В  папке маршрутов  создайте один файл с именем business.route.js.

Напишите код CRUD в  файле 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;

Мы использовали модель мангуста для сохранения, обновления и удаления базы данных. Mongoose — это ORM , используемая в базе данных MongoDB . У нас настроены все операции 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. Проверьте функциональность данных магазина

Если все серверы запущены и работают, вы можете зайти в браузер, заполнить данные формы и добавить бизнес. Вы можете увидеть что-то подобное на своем экране, если вы добились успеха.

Теперь мы можем проверить базу данных, используя следующие команды.

Сначала откройте оболочку монго на 4-й вкладке, потому что все остальные три вкладки в данный момент заняты.

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: Редактировать и обновлять данные

Хорошо, во-первых, нам нужно получить данные из базы данных MongoDB, используя _id, и отобразить эти данные в файле 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  нам нужно  закодировать функцию editBusiness  для отправки 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}`);
    }
}

Наконец, нам нужно написать форму внутри файла 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>

Сохраните файл, перейдите на страницу листинга, нажмите кнопку редактирования и увидите заполненную форму из базы данных.

Вы также можете увидеть предупреждение, как показано ниже. Не обращайте внимания на этот демонстрационный урок.

form.js:1193
Похоже, вы используете ngModel в том же поле формы, что и formControlName.
Поддержка использования входного свойства ngModel и события ngModelChange с
директивами реактивной формы устарела в Angular v6 и удалена
в Angular v7.

Теперь обновите данные. Внутри файла  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'));
  }

Хорошо, теперь напишите  функцию updateBusiness()  в файле 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']);
});

Сохраните файл, и вы сможете обновить данные.

17: Удалить данные.

Итак, если вы не найдете ошибок в консоли, вы можете успешно обновить данные.

Я уже написал службу редактирования  и  обновления  для вызовов API. Итак, на данный момент создание, чтение, обновление  завершено в этом  примере Angular CRUD . Теперь взгляните на  Удалить .

Нам нужно определить событие нажатия на кнопку удаления в  файле 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');
    });
  }

Наконец, создайте функцию deleteBusiness()  в файле business.service.ts  .

// business.service.ts

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

Наконец, я завершил функцию удаления.

Итак, в этом уроке мы завершили функциональность CRUD в Angular.
 

CODE VN

CODE VN

1646515620

Xây dựng ứng dụng web Crud bằng Angular | Angular 13 CRUD

Angular CRUD có nghĩa là một ứng dụng bao gồm tạo, đọc, cập nhật và xóa các chức năng dữ liệu. Đây là hướng dẫn toàn diện về cách xây dựng các ứng dụng web CRUD (Tạo, Đọc, Cập nhật, Xóa) bằng cách sử dụng Khuôn khổ Angular Mới. Angular vừa được phát hành và nó đi kèm với một số tính năng và cải tiến mới.

Đầu tiên, chúng tôi sẽ cài đặt Angular bằng Angular CLI, sau đó chúng tôi sẽ tiếp tục phát triển frontend và backend.

1: Cài đặt Angular và các phụ thuộc khác.

Nếu bạn có phiên bản @ angle / cli cũ hơn, bạn có thể chạy lệnh sau để cài đặt các phiên bản mới nhất.

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

Nếu bạn đang gặp phải bất kỳ sự cố nào, vui lòng xem Cách cập nhật Angular CLI lên phiên bản 7 của tôi . Nó sẽ giúp bạn cập nhật Angular CLI và bạn sẽ tạo một dự án Angular bảy hoàn toàn mới.

Được rồi, bây giờ, nếu bạn gõ lệnh sau, bạn có thể thấy rằng chúng tôi đã cập nhật Angular CLI.

Ví dụ về Angular 7 CRUD |  Hướng dẫn về ngăn xếp MEAN

Bây giờ, bạn sẽ tạo một dự án Angular mới bằng lệnh sau.

ng new angular7crud
cd angular7crud

Ví dụ về MEAN Stack CRUD

Sau khi vào bên trong thư mục dự án, hãy mở dự án trong Visual Studio Code bằng lệnh sau. Nếu bạn không sử dụng nó, sau đó bắt đầu sử dụng nó. Nó là Trình chỉnh sửa tốt nhất để phát triển Javascript .

code .

Tại thời điểm cài đặt, chúng tôi đã bật định tuyến cho ứng dụng của mình. Nó là mới trong Angular  vì nó sẽ nhắc chúng ta trong khi cài đặt boilerplate góc. Bạn có thể kiểm tra tệp có tên tệp app-routing.module.ts  bên trong thư mục src >> app .

Tiếp theo, cài đặt Bootstrap 4 CSS Framework bằng lệnh sau.

npm install bootstrap --save

Bây giờ, thêm nó vào bên trong  tệp angle.json  .

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

Vì vậy, bây giờ chúng ta có thể sử dụng các lớp Bootstrap 4 trong dự án của mình. 

Khởi động máy chủ phát triển Angular bằng lệnh sau.

ng serve -o

 

Hướng dẫn Angular 7

mô tả dự án

Chúng tôi sẽ tạo một dự án trong đó người dùng có thể nhập Tên người dùng  , Tên doanh nghiệp  và Số GST của họ từ biểu mẫu và gửi nó. Nếu các giá trị không chính xác, chúng sẽ xác thực ở giao diện người dùng và biểu mẫu sẽ không được gửi. Mặt khác, nếu tất cả các giá trị có vẻ hoàn hảo, chúng tôi sẽ gửi biểu mẫu đến API phụ trợ , lưu trữ các giá trị bên trong cơ sở dữ liệu MongoDB .

Vì vậy, bây giờ, chúng ta sẽ tạo một số thành phần góc cạnh để thực hiện công việc.

2: Tạo các thành phần Angular

Gõ lệnh sau để tạo các Thành phần Angular . Chúng tôi sẽ thực hiện các thao tác tạo, đọc, cập nhật. Vì vậy, chúng tôi sẽ tạo ra ba thành phần.

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

Hướng dẫn sử dụng CRUD góc

Tất cả ba thành phần được đăng ký tự động bên trong tệp app.module.ts  . Chúng ta cần định cấu hình định tuyến của các thành phần góc bên trong tệp 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 { }

Bây giờ, bạn có thể thấy bên trong  tệp app.component.html  có chỉ thị <router-outlet>  . Chỉ thị này giúp chúng tôi hiển thị các thành phần khác nhau dựa trên URI tuyến.

3: Tạo điều hướng góc

Viết mã sau vào trong  tệp 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>

Lưu tệp và truy cập trình duyệt và nhấp vào hai liên kết. Bạn có thể thấy rằng chúng ta có thể thấy các thành phần khác nhau dựa trên điều hướng.

4: Cài đặt Chỉ báo Tiến trình Định tuyến Angular.

Gõ lệnh sau để cài đặt  thư viện ng2-slim-loading-bar .

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

Vì vậy, nếu bạn cài đặt các gói của bên thứ ba ngay bây giờ, nó sẽ không tương thích với Angular . Để thu hẹp khoảng cách giữa  Angular  và các gói của bên thứ ba, chúng ta cần cài đặt thư viện sau. Đó là nó.

npm install rxjs-compat --save

Bây giờ, nhập  SlimLoadingBarModule  bên trong  tệp app.module.ts  .

// app.module.ts

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

imports: [
    ...
    SlimLoadingBarModule
],

Bước tiếp theo là bao gồm tạo kiểu với thư viện bên trong tệp src >> styles.css  .

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

5: Thêm sự kiện bộ định tuyến.

Angular RouterModule cung cấp cho chúng ta các mô-đun sự kiện sau.

  1. NavigationStart
  2. NavigationEnd
  3. NavigationError
  4. NavigationCancel
  5. Bộ định tuyến
  6. Biến cố

Bây giờ, hãy viết đoạn mã sau bên trong  tệp 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();
    }
  }
}

Nó đang làm việc đó là chặn sự kiện định tuyến và thêm thành phần thanh tải vào mọi tuyến đường để chúng tôi có thể thấy chỉ báo định tuyến mỗi khi chúng tôi thay đổi các tuyến đường.

Thay đổi cuối cùng để hiển thị chỉ báo định tuyến là thêm chỉ thị ng2-slim-loading-bar bên trong  tệp app.component.html  ở đầu trang.

<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>

Lưu tệp và đi đến thiết bị đầu cuối để xem có lỗi không và nếu không, hãy vào trình duyệt và thay đổi các tuyến, và bạn có thể thấy rằng bây giờ chúng ta có thể thấy chỉ báo định tuyến.

6: Thêm biểu mẫu Bootstrap

Bên trong  tệp gst-add.component.html  , thêm  biểu mẫu bootstrap 4 sau .

<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 7 CRUD Demo

7: Thêm xác thực biểu mẫu góc cạnh

Chúng tôi sẽ sử dụng ReactiveFormsModule . Vì vậy, nếu bạn chưa quen với Angular Form Validation , hãy xem bài viết này của tôi về Angular Form Validation  trên blog này.

Bây giờ, nhập  ReactiveFormsModule  bên trong  tệp app.module.ts  .

// app.module.ts

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

imports: [
    ...
    ReactiveFormsModule
],

Bây giờ, chúng ta cần viết mã cho  tệp app.component.ts  . Hãy nhớ rằng, đây không phải là một biểu mẫu theo hướng mẫu. Vì vậy, chúng tôi sẽ thay đổi mã bên trong tệp app.component.ts  .

Đầu tiên, chúng tôi nhập các  mô-đun FormGroup, FormBuilder, Validators  từ  @ angle / form .

Ngoài ra, hãy tạo một phương thức khởi tạo và khởi tạo  FormBuilder .

Vì vậy, hãy viết đoạn mã sau bên trong  tệp 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() {
  }

}

Chúng tôi đã sử dụng trình tạo biểu mẫu để xử lý tất cả các xác thực. Vì vậy, trong hàm tạo đó, chúng ta đang tạo một biểu mẫu với các quy tắc xác thực. Trong ví dụ của chúng tôi, có ba trường. Nếu văn bản đầu vào trống, nó sẽ báo lỗi và chúng ta cần hiển thị nó.

Bây giờ, hãy viết đoạn mã sau vào trong  tệp 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>

Lưu tệp và vào trình duyệt, và bạn có thể thấy nếu bạn không đặt bất kỳ giá trị nào bên trong hộp nhập liệu, bạn sẽ thấy các lỗi.

Ví dụ về xác thực biểu mẫu Angular 7

8: Định cấu hình HttpClientModule

Nhập  HttpClientModule  bên trong  tệp app.module.ts  .

// app.module.ts

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

imports: [
   ...
    HttpClientModule
 ],

9: Tạo mô hình.

Bên trong  thư mục ứng dụng src >>  , tạo một tệp có tên  Business.ts  và thêm mã sau.

// Business.ts

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

10: Tạo tệp Angular Service.

Nhập lệnh sau để tạo tệp dịch vụ.

ng g service business --spec=false

Vì vậy, tệp business.service.ts  chính của bạn  trông giống như thế này.

// business.service.ts

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

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

  constructor() { }
}

Bây giờ, hãy nhập  tệp business.service.ts  vào  tệp app.module.ts  .

// app.module.ts

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

providers: [ BusinessService ],

11: Gửi dữ liệu đến máy chủ nút

Chúng ta cần viết mã sẽ gửi yêu cầu HTTP POST với dữ liệu đến máy chủ Node.js và lưu dữ liệu vào cơ sở dữ liệu MongoDB .

Viết mã sau vào  tệp 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'));
  }
}

Chúng tôi đã xác định URL API phụ trợ của mình, nhưng chúng tôi chưa tạo bất kỳ chương trình phụ trợ nào, nhưng chúng tôi sẽ thực hiện điều đó trong một vài bước.

Chúng ta cần thêm sự kiện nhấp chuột vào Nút Thêm Doanh nghiệp. Vì vậy, hãy thêm mã sau vào trong tệp 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>

Vì vậy, khi không có lỗi, chúng tôi có thể gửi biểu mẫu, và nó sẽ gọi  hàm addBusiness  của thành phần . Từ đó, chúng ta sẽ gọi dịch vụ góc và dịch vụ sẽ gửi yêu cầu HTTP Post đến máy chủ Node.js.

Bây giờ, hãy thêm  hàm addBusiness  vào bên trong  tệp gst-add.component.ts  . Vì vậy, hãy viết đoạn mã sau bên trong  tệp 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() {
  }

}

Ở đây, chúng tôi đã xác định hàm và cũng nhập  tệp business.service.ts  . Tiếp theo, khởi tạo đối tượng bên trong hàm tạo và gọi hàm của tệp businsess.service.ts .

Chúng tôi đã mã hóa  hàm addBusiness  bên trong  tệp business.service.ts  . Bây giờ, chúng ta cần định cấu hình API phụ trợ.

12: Tạo một API phụ trợ Node.js

Bên trong thư mục gốc góc, tạo một thư mục có tên api và vào bên trong thư mục đó. Hãy nhớ rằng, nó sẽ là một dự án hoàn toàn riêng biệt với Angular. Vì vậy, node_modules của nó khác với Angular .

Mở thiết bị đầu cuối bên trong  thư mục api  và nhập lệnh sau.

npm init -y

Cài đặt các mô-đun dành riêng cho nút sau.

npm install --save express body-parser cors mongoose

Tôi không khởi động lại máy chủ nút mỗi lần; Tôi thay đổi tệp. Vì vậy, tôi đang cài đặt máy chủ gật đầu. Những gì nó làm là khi tôi sửa đổi tệp server.js  , nó sẽ tự động khởi động lại  máy chủ node.js. 

npm install nodemon --save-dev

Bây giờ, bên trong  thư mục api  , hãy tạo một tệp được gọi là  tệp 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);
    });

Điều tiếp theo là kết nối cơ sở dữ liệu MongoDB với ứng dụng node.js của chúng tôi.

Nếu bạn chưa cài đặt cơ sở dữ liệu MongoDB, hãy cài đặt nó và khởi động máy chủ mongodb.

Nhập lệnh sau để khởi động  máy chủ MongoDB  .

mongod

Vì vậy, Bây giờ, tôi đã kết nối với cơ sở dữ liệu.

Tạo một tệp có tên  DB.js  bên trong  thư mục dự án gốc api  . Sau đó, viết đoạn mã sau vào trong tệp DB.js. 

// DB.js

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

Nhập  tệp DB.js này vào bên trong tệp server.js  của chúng tôi  và sử dụng  thư viện mongoose  để thiết lập  kết nối cơ sở dữ liệu  với  MongoDB . Chúng ta cũng có thể sử dụng Mongoose để lưu dữ liệu trong cơ sở dữ liệu bằng Mongoose ORM.

Viết mã sau bên trong tệp  server.js  để kết nối ứng dụng  MongoDB  của chúng tôi với máy chủ 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);
    });

Lưu tệp và đi đến thiết bị đầu cuối và khởi động máy chủ nút.

nodemon server

Vì vậy, ngay bây giờ, bạn có ba máy chủ đang chạy.

  1. Máy chủ phát triển góc
  2. Máy chủ Nodemon
  3. Máy chủ MongoDB

Hãy nhớ rằng, cả ba máy chủ đều chạy tốt mà không có bất kỳ lỗi nào; nếu không, ứng dụng của chúng tôi sẽ không hoạt động.

Bước 13: Tạo mô hình và các tuyến đường cho ứng dụng của chúng tôi.

Chúng ta cần tạo hai thư mục bên trong thư mục gốc api được gọi là các tuyếnmô hình .

Trong thư mục mô hình  , hãy tạo một mô hình có tên là  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);

Vì vậy, chúng tôi đã xác định lược đồ của mình cho bộ sưu tập doanh nghiệp. Chúng tôi có ba trường được gọi là  person_name, business_name, business_gst_number.

Trong  thư mục định tuyến  , hãy tạo một tệp có tên business.route.js.

Viết mã CRUD bên trong  tệp 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;

Chúng tôi đã sử dụng mô hình mongoose để lưu, cập nhật và xóa cơ sở dữ liệu. Mongoose là một ORM được sử dụng trong cơ sở dữ liệu MongoDB . Chúng tôi có tất cả các hoạt động CRUD được thiết lập trên tệp tuyến đường; chúng ta cần nhập chúng vào bên trong tệp server.js  .

Vì vậy, tệp server.js  cuối cùng của chúng tôi  trông như thế này.

// 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);
});

Bước 14: Kiểm tra chức năng dữ liệu lưu trữ

Nếu tất cả các máy chủ đang hoạt động, bạn có thể truy cập trình duyệt, điền vào dữ liệu biểu mẫu và thêm doanh nghiệp. Bạn có thể thấy một cái gì đó như thế này trên màn hình của bạn nếu bạn thành công.

Bây giờ, chúng ta có thể kiểm tra cơ sở dữ liệu bằng các lệnh sau.

Đầu tiên, hãy mở trình bao mongo trên tab thứ 4 vì tất cả ba tab còn lại đều bị chiếm dụng tại thời điểm này.

mongo

Ở đây, chúng ta có thể thấy rằng các giá trị được lưu trữ trong cơ sở dữ liệu MongoDB. Vâng!! Chúng tôi đã thành công.

Bây giờ, các thao tác còn lại là Đọc, Cập nhật và Xóa.

15: Hiển thị dữ liệu trên giao diện người dùng

Trong tệp gst-get.component.html  , hãy viết mã sau.

<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>

Bây giờ, bên trong  tệp business.service.ts  , chúng ta cần viết hàm tìm nạp dữ liệu nghiệp vụ từ  cơ sở dữ liệu MongoDB và hiển thị nó tại ứng dụng Angular .

// business.service.ts

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

Chúng tôi cần bao gồm tệp business.service.ts  này và tệp Business.ts  bên trong tệp  gst-get.component.ts  .

Viết đoạn mã sau vào trong  tệp 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;
    });
  }
}

Lưu tệp, truy cập trình duyệt và chuyển sang URL này:  http: // localhost: 4200 / business. Bạn có thể xem danh sách của các doanh nghiệp.

16: Chỉnh sửa và cập nhật dữ liệu

Được rồi, trước tiên, chúng ta cần tìm nạp dữ liệu từ cơ sở dữ liệu MongoDB bằng _id khôn ngoan và hiển thị dữ liệu đó trong tệp gst-edit.component.html  .

Vì vậy, trước tiên, hãy viết đoạn mã sau bên trong  tệp 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;
      });
    });
  }
}

Tại đây, khi  gst-edit component.ts  kết xuất, nó sẽ gọi  phương thức ngOnInit  và gửi một yêu cầu HTTP đến máy chủ nút và tìm nạp dữ liệu từ một _id để hiển thị bên trong  tệp gst-edit.component.html  .

Bây giờ, bên trong  tệp business.service.ts  , chúng ta cần mã  hóa hàm editBusiness  để gửi một yêu cầu 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}`);
    }
}

Cuối cùng, chúng ta cần viết biểu mẫu bên trong tệp 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>

Lưu tệp, đi đến trang danh sách, nhấp vào nút chỉnh sửa và xem biểu mẫu được điền từ cơ sở dữ liệu.

Bạn cũng có thể thấy cảnh báo như sau. Bỏ qua hướng dẫn demo này.

form.js: 1193
Có vẻ như bạn đang sử dụng ngModel trên cùng một trường biểu mẫu với formControlName.
Hỗ trợ sử dụng thuộc tính đầu vào ngModel và sự kiện ngModelChange với các
chỉ thị biểu mẫu phản ứng đã không được chấp nhận trong Angular v6 và bị loại bỏ
trong Angular v7.

Bây giờ, hãy cập nhật dữ liệu. Bên trong tệp  business.service.ts  , chúng ta cần viết hàm cập nhật dữ liệu.

// 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'));
  }

Được rồi, bây giờ hãy viết hàm  updateBusiness ()  bên trong tệp 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']);
});

Lưu tệp và bạn sẽ có thể cập nhật dữ liệu.

17: Xóa dữ liệu.

Vì vậy, nếu bạn không tìm thấy lỗi nào trên bảng điều khiển, bạn có thể cập nhật dữ liệu thành công.

Tôi đã viết một dịch vụ chỉnh sửa  và  cập nhật  để thực hiện các lệnh gọi API. Vì vậy, cho đến nay, Tạo, Đọc, Cập nhật  đã hoàn tất cho  Ví dụ Angular CRUD này . Bây giờ, hãy xem  Xóa .

Chúng ta cần xác định sự kiện nhấp chuột vào nút xóa bên trong tệp  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>

Bây giờ, hãy viết  hàm deleteBusiness  bên trong  tệp gst-get.component.ts  .

// gst-get.component.ts

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

Cuối cùng, tạo hàm deleteBusiness ()  bên trong tệp business.service.ts  .

// business.service.ts

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

Cuối cùng, tôi đã hoàn thành chức năng xóa.

Như vậy, trong hướng dẫn này, chúng ta đã hoàn thành Chức năng CRUD trong Angular.