1671716940
The report's single focus will be on cross-cultural communication, which was a competence that was developed as a worldwide manager. This piques my attention personally because communication not only focuses on interactions with people from diverse cultural backgrounds but also develops a deeper understanding of people in order to fulfil expectations and motivates staff to work harder in order to achieve organisational objectives. The fundamental principles of human interaction and the implications for appropriate behaviours in response to that form of interaction are connected together by aspects of communication. It takes more than just learning a language to assimilate into another culture; one must also adopt behaviours that support that acceptance. According to Hofstede, culture includes the ways in which a group of people distinguishes itself from others and shapes how things are viewed (Hofstede 2004). From a commercial perspective, a person's familiarity with cultural norms and protocol can have a significant impact on how key organisational choices turn out. In order to be productive in an organisation as a future global manager, one must continue to build their multicultural communication abilities. A leader in an organisation should be able to communicate his or her strategies to the team members so that they can work together to accomplish the same objectives. This will help the management team flourish in the highly competitive global business environment. For example, Australia, one of the world's most multicultural nations, has created a culture for its citizens from many ethnic backgrounds so that they can help the country build a brighter future. Daily interactions with a variety of people might affect one's perspective of a person in the workforce, in addition to other reasons. Therefore, I think that being exposed to a multicultural atmosphere will alter one's perspective and make them aware of the value of being in a multicultural setting.
The wider definition of intercultural communication, opposing viewpoints and discussions on the subject, as well as how this issue might benefit my future as a global manager in a multicultural setting, will all be covered in the essay writing services.
Definition
In today's heterogeneous culture, intercultural communication has grown in importance for a lot of people. Modern enterprises are becoming considerably more globalised, where the transfer of goods and services from one nation to another stimulates economic growth. After one understands the challenges of a manager and the context it delivers to, cross-cultural communication falls under the category of learning management abilities (Deng 2019). Understanding and compassion for other cultures are essential components of effective cross-cultural communication. Companies nowadays need to be increasingly adept at navigating cross-cultural environments since doing so will help them acquire exposure to global markets and increase future profitability (Pikhart 2014). When talking about culture, one should take into account the sociocultural norms of a certain nation or the workers at a particular organisation. Theoretically, it is crucial to talk about social structure, religion, aesthetics, values, and interpersonal communication. Language is not the only factor in the growing influx of migrants and commercial mobility; rather, it aids in a person's comprehension of a country's politics, economy, and other factors (Sison 2017). Many businesses travel abroad in pursuit of access to the global market, but not all of them may be successful due to a lack of understanding of the socioeconomic culture of the destination nation.
Quickly evolving business sectors
Rapid changes in many business industries play a significant role in hiring workers (and graduates), who are not only focused on communication skills for better delivery of business goals but also on competency in technological abilities (Rourke et al. 2019). When individuals possess superior skills that can be applied to enhancing job quality and establishing powerful management networks, businesses tend to succeed. A detailed investigation of a nation's operations may greatly deepen understanding and open up prospective new markets. Becoming able to observe, comprehend, and respond appropriately within the context of the culture may prevent someone from being offended, which is a component of cultural competency.
Additionally, it's crucial for a management of a worldwide company to take Hofstede's Cultural Dimensions into account. The idea of individualism and collectivism, where various cultures survive on interdependence, is one of the elements of this dimension. One of the dimensions, masculinity, suggests that society needs to be more competitive (Hofstede Insights, 2019). urging customers to choose specific goods and/or services in accordance with cultural norms that they may identify with in their daily lives (Laufer 2010). Since advertisements can be seen differently depending on the culture, it is important to know how to portray marketable products in a way that is respectful of that culture. That may be observed in the marketing strategies used in the US and Russia, where the use of images may be interpreted differently depending on the popularity of the brand and the culture of the mainstream media (Mikhailitchenko 2009). Additionally highlighting the issue of power distance, Hofstede's Cultural Dimensions analyses the unequal distribution of power (hierarchy). The degree to which the less powerful members of institutions and organisations within a nation assume and accept that power is allocated unequally is known as "power gap" (Hofstede Insights 2019). This can be seen in circumstances when intercultural talks take place, where individuals or groups of people from different cultures tend to conflict and then fail to consider how the hierarchical emphasis has an emotional impact (Liu et al 2016). There is a gap between management and employees in several Asian nations where conversations were limited to directors and managers. These are a few examples of the kinds of indicators that provide managers with a framework for identifying cultural differences in approaches to communication.
Literary conflict in regard to subject
Multinational firms will still have to deal with a variety of difficulties that prohibit them from taking full advantage of the global market. Miscommunication is frequently one of the main causes of a chain of issues that could easily ruin an international relationship. Even though English is frequently used as a global standard language, it can still be challenging for those whose first language is another to understand. Therefore, it is simple to form a cultural stereotype since a lack of cultural awareness and information may lead to a breakdown in cross-cultural relationships. Although nonverbal communication such as gestures, personal space, tone, and so on should also be taken into account when communicating across cultural boundaries, one should also take into account all other features of that culture (Myarticles). Non-native speakers with great technical skill who are perceived as unprepared owing to the language barrier may be hindered in the case of global organisations where English was employed as the primary language (Wang et al. 2018). The productivity of managers and employees is one of a well-funded organization's greatest assets. It is difficult to motivate employees to pursue them in order to obtain the greatest input if the workplace's standards are not met. Additionally, it may cause them to work poorly, steal, and put off finishing responsibilities, which impedes the ability of enterprises to move forward (Jiang et al. 2016). Employees that are discouraged will never be able to devote themselves totally to their work, leading to a dysfunctional office environment and unfinished projects. Due to a lack of cultural sensitivity, potential business partnerships may be derailed, hurting the organization's reputation over time. Local businesses may fail to recognise that multinational enterprises' strength lies in their ability to successfully acquire both domestic markets and cultural competence (Rupidara & Darby 2016).
Additionally, as a global manager, you must take into account local customs and business protocol. The most crucial aspect that must be taken into account during meetings and greetings is a manager's first impression. This issue still causes friction, particularly when it comes to cultures that are more complex and effect how the business interacts with one another. For instance, it's important to bow first when greeting someone in Japan at a 45-degree angle to show them respect. The principle of honouring people through their language and gestures guides Japanese behaviour, and they place a lot of value on politeness (Dunn 2011). Additionally, while greeting someone in nations like Sri Lanka or India, it's important to use the greetings "yubovan" or "Namaste" (Deng 2019). The right things to address during meetings is another issue that arises in cross-cultural communication. There is a good likelihood that you are developing perfect trust between each other if you have the correct motivation when approaching someone with a strong cultural background.
Why is this topic crucial to me if I wish to work as a manager across cultures?
In general, an excellent manager would always seek out ways to improve both personal growth and team morale. As a manager, I feel responsible for passing on the abilities people will need to succeed both at work and outside of it. Every credible organisation should be judged on the strength of its executives rather than the size of its global operations. It is essential to provide workers with so they can view the workplace from the same perspective as other employees. The biggest influence on creating a workable solution for the long-term development of the company may come from a thorough review of the organisational environment. Speaking two languages fluently and living abroad in Indonesia have given me a broader grasp of how to apply solutions to various organisational settings. Diverse countries have different work cultures, therefore adaptations are often required to effectively connect with those around you. Without effective communication among the board of directors, management, and employees, well-executed business strategy would fail. Another helpful element is presenting a positive image of the organisation, especially when speaking with prospective customers and business partners. People should be able to read at the same level regardless of what their job entails in order to make judgements and prevent misunderstandings (Patel 2015). Information exchange has grown so crucial that even a small error could cause the corporate process to become disorganised.
What I learnt about the subject and how I plan to apply it in the future
This subject aids in my further analysis of the best communication techniques to employ while strategically negotiating with people from different cultural backgrounds. It is extremely important for firms to develop presence in various nations because business methods and culture aren't always linked. We should learn intercultural communication skills in order to solve the issue of unequal access to the associated economic, political, and other opportunities if we want to operate as a global manager. Another crucial element is experience with cross-cultural collaboration, simply because learning theories is insufficient in and of itself without encountering difficulties or issues. As a non-native English speaker, attending a university with a varied student body allowed me to develop personally and broaden my perspective as a member of the world community. Working on group projects or participating in overseas study tours, these chances impacted people's perspectives on various cultures without them even realising it. Your position or financial standing in another country may be important or unimportant to some cultures, depending on the culture. My personal interactions with workers from various cultural backgrounds in Indonesia have also taught me that certain behaviours and actions have a significant impact on how others perceive me. In Indonesian workplace etiquette, hierarchy has always been stressed; however, people of other nationalities are not used to it, which causes difficulties between management and employees. It is crucial to recognise both an organization's objective and the cornerstone of its management strategy in Indonesia because perceptions of privilege or higher management position may alter how we interact with others (Rupidara & Darby 2017). I firmly believe that effective communication can lessen conflict, particularly between coworkers or romantic partners from diverse cultural backgrounds. In the end, having this knowledge will help me decide whether to expand my business operations outside of Indonesia. As I continue my quest to develop my cross-cultural communication skills, this will help me stand out from my rivals. For me, it was important to acknowledge the many cultural experiences because I believe that respectful contact between people should involve more than just acceptance.
1595491178
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.
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.
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.
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
Specifications
Why Should You Buy This?
**Who Should Ride Billy? **
Both new and experienced riders
**Where to Buy? **Local distributors or ships from the USA.
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
Specifications
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
Specifications
http://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
Specifications
#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
1595494844
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.
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.
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.:
#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
1608807115
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.
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.
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.
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.
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
1646493670
Angular CRUD bezeichnet eine Anwendung, die aus Erstellung, Lesen, Aktualisieren und Löschen von Datenfunktionalitäten besteht. Es ist die umfassende Anleitung zum Erstellen von CRUD-Webanwendungen (Create, Read, Update, Delete) mit dem New Angular Framework. Der Angular wurde gerade veröffentlicht und enthält einige neue Funktionen und Verbesserungen.
Zuerst werden wir Angular mit Angular CLI installieren und dann das Frontend und Backend weiterentwickeln.
Wenn Sie eine ältere @angular/cli-Version haben, können Sie den folgenden Befehl ausführen, um die neuesten Versionen zu installieren.
npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli
Wenn Sie irgendwelche Probleme haben, lesen Sie bitte mein How To Update Angular CLI To Version 7 . Es wird Ihnen helfen, Ihre Angular CLI zu aktualisieren , und Sie werden ein brandneues Angular Seven-Projekt erstellen.
Okay, wenn Sie jetzt den folgenden Befehl eingeben, können Sie sehen, dass wir Angular CLI aktualisiert haben.
Jetzt erstellen Sie mit dem folgenden Befehl ein neues Angular-Projekt.
ng new angular7crud
cd angular7crud
Nachdem Sie in den Projektordner gegangen sind, öffnen Sie das Projekt in Visual Studio Code mit dem folgenden Befehl. Wenn Sie es nicht verwenden, beginnen Sie damit, es zu verwenden. Es ist der beste Editor für die Javascript- Entwicklung.
code .
Zum Zeitpunkt der Installation haben wir das Routing für unsere Anwendung aktiviert. Es ist neu in Angular , weil es uns bei der Installation der eckigen Boilerplate auffordert. Sie können die Datei mit dem Namen app-routing.module.ts im Verzeichnis src >> app überprüfen .
Installieren Sie als Nächstes das Bootstrap 4 CSS Framework mit dem folgenden Befehl.
npm install bootstrap --save
Fügen Sie es jetzt in die Datei angle.json ein .
"styles": [
"src/styles.css",
"./node_modules/bootstrap/dist/css/bootstrap.min.css"
],
Jetzt können wir die Bootstrap 4-Klassen in unserem Projekt verwenden.
Starten Sie den Angular-Entwicklungsserver mit dem folgenden Befehl.
ng serve -o
Wir werden ein Projekt erstellen, bei dem Benutzer ihren Benutzernamen , Firmennamen und ihre GST-Nummer aus dem Formular eingeben und absenden können. Wenn die Werte falsch sind, werden sie am Frontend validiert und das Formular wird nicht gesendet. Wenn andererseits alle Werte perfekt erscheinen, senden wir das Formular an die Backend-API und speichern die Werte in der MongoDB- Datenbank.
Also werden wir jetzt einige Winkelkomponenten erstellen, um die Arbeit zu erledigen.
Geben Sie den folgenden Befehl ein, um Angular Components zu generieren . Wir führen Erstellungs-, Lese- und Aktualisierungsvorgänge durch. Also werden wir drei Komponenten erstellen.
ng g c gst-add --spec=false
ng g c gst-get --spec=false
ng g c gst-edit --spec=false
Alle drei Komponenten werden automatisch in einer app.module.ts - Datei registriert. Wir müssen das Routing von Winkelkomponenten in einer app-routing.module.ts- Datei konfigurieren.
// 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 { }
Jetzt können Sie in der Datei app.component.html sehen , dass die Direktive <router-outlet> vorhanden ist. Diese Direktive hilft uns beim Rendern der verschiedenen Komponenten basierend auf dem Routen-URI.
Schreiben Sie den folgenden Code in die Datei 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>
Speichern Sie die Datei und gehen Sie zum Browser und klicken Sie auf zwei Links. Sie können sehen, dass wir die verschiedenen Komponenten basierend auf der Navigation sehen können.
Geben Sie den folgenden Befehl ein, um die Bibliothek ng2-slim-loading-bar zu installieren .
npm install ng2-slim-loading-bar --save
Wenn Sie also jetzt Pakete von Drittanbietern installieren, ist es nicht mit Angular kompatibel . Um die Lücke zwischen Angular und Paketen von Drittanbietern zu schließen, müssen wir die folgende Bibliothek installieren. Das ist es.
npm install rxjs-compat --save
Importieren Sie nun das SlimLoadingBarModule in die Datei app.module.ts .
// app.module.ts
import { SlimLoadingBarModule } from 'ng2-slim-loading-bar';
imports: [
...
SlimLoadingBarModule
],
Der nächste Schritt besteht darin, das Styling mit der Bibliothek in die Datei src >> styles.css aufzunehmen .
@import "../node_modules/ng2-slim-loading-bar/style.css";
Angular RouterModule gibt uns die folgenden Ereignismodule.
Schreiben Sie nun den folgenden Code in die Datei 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();
}
}
}
Es fängt das Routing-Ereignis ab und fügt die Ladebalkenkomponente zu jeder Route hinzu, sodass wir die Routing-Anzeige jedes Mal sehen können, wenn wir die Routen ändern.
Die letzte Änderung zur Anzeige des Routing-Indikators besteht darin, die Direktive ng2-slim-loading-bar in der Datei app.component.html oben auf der Seite hinzuzufügen.
<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>
Speichern Sie die Datei und gehen Sie zum Terminal, um zu sehen, ob ein Fehler vorliegt, und wenn nicht, gehen Sie zum Browser und ändern Sie die Routen, und Sie können sehen, dass wir jetzt die Routing-Anzeige sehen können.
Fügen Sie in der Datei gst -add.component.html das folgende Bootstrap-4 - Formular hinzu.
<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>
Wir werden ReactiveFormsModule verwenden . Wenn Sie neu bei der Angular Form Validation sind , lesen Sie bitte diesen Artikel Angular Form Validation in diesem Blog.
Importieren Sie nun das ReactiveFormsModule in die Datei app.module.ts .
// app.module.ts
import { ReactiveFormsModule } from '@angular/forms';
imports: [
...
ReactiveFormsModule
],
Jetzt müssen wir den Code für die Datei app.component.ts schreiben . Denken Sie daran, dass dies kein vorlagengesteuertes Formular ist. Also werden wir den Code in der Datei app.component.ts ändern .
Zuerst importieren wir die Module FormGroup, FormBuilder, Validators aus @angular/forms .
Erstellen Sie außerdem einen Konstruktor und instanziieren Sie den FormBuilder .
Schreiben Sie also den folgenden Code in die Datei 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() {
}
}
Wir haben den Form Builder verwendet, um die gesamte Validierung durchzuführen. In diesem Konstruktor erstellen wir also ein Formular mit den Validierungsregeln. In unserem Beispiel gibt es drei Felder. Wenn der Eingabetext leer ist, wird ein Fehler ausgegeben und wir müssen ihn anzeigen.
Schreiben Sie nun den folgenden Code in die Datei 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>
Speichern Sie die Datei und gehen Sie zum Browser, und Sie können sehen, wenn Sie keinen Wert in das Eingabefeld eingeben, sehen Sie die Fehler.
Importieren Sie das HttpClientModule in die Datei app.module.ts .
// app.module.ts
import { HttpClientModule } from '@angular/common/http';
imports: [
...
HttpClientModule
],
Erstellen Sie im App -Ordner src >> eine Datei mit dem Namen Business.ts und fügen Sie den folgenden Code hinzu.
// Business.ts
export default class Business {
person_name: String;
business_name: String;
business_gst_number: Number;
}
Geben Sie den folgenden Befehl ein, um die Dienstdatei zu generieren.
ng g service business --spec=false
Ihre primäre business.service.ts -Datei sieht also so aus.
// business.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class BusinessService {
constructor() { }
}
Importieren Sie nun die Datei business.service.ts in die Datei app.module.ts .
// app.module.ts
import { BusinessService } from './business.service';
providers: [ BusinessService ],
Wir müssen den Code schreiben, der die HTTP -POST-Anforderung mit den Daten an den Node.js -Server sendet, und die Daten in der MongoDB - Datenbank speichern.
Schreiben Sie den folgenden Code in die Datei 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'));
}
}
Wir haben unsere Backend-API-URL definiert, aber wir haben noch kein Backend erstellt, aber wir werden es in ein paar Schritten tun.
Wir müssen das Click-Ereignis zum Add Business Button hinzufügen. Fügen Sie also den folgenden Code in die Datei gst-add.component.html ein .
<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>
Wenn also keine Fehler vorliegen, können wir das Formular absenden, und es ruft die addBusiness - Funktion der Komponente auf. Von dort aus rufen wir den Winkeldienst auf, und der Dienst sendet die HTTP - Post-Anfrage an den Node.js -Server.
Fügen Sie nun die Funktion addBusiness in der Datei gst-add.component.ts hinzu . Schreiben Sie also den folgenden Code in die Datei 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() {
}
}
Hier haben wir die Funktion definiert und auch die Datei business.service.ts importiert. Instanziieren Sie als Nächstes das Objekt im Konstruktor und rufen Sie die Funktion der Datei businness.service.ts auf .
Wir haben die Funktion addBusiness bereits in der Datei business.service.ts codiert . Jetzt müssen wir die Backend-API konfigurieren.
Erstellen Sie im eckigen Stammordner einen Ordner mit dem Namen api und gehen Sie in diesen Ordner. Denken Sie daran, dass es ein völlig separates Projekt von Angular sein wird. Seine node_modules unterscheiden sich also von einem Angular .
Öffnen Sie das Terminal im API -Ordner und geben Sie den folgenden Befehl ein.
npm init -y
Installieren Sie die folgenden knotenspezifischen Module.
npm install --save express body-parser cors mongoose
Ich starte den Knotenserver nicht jedes Mal neu; Ich ändere die Datei. Also installiere ich den Nodemon-Server. Wenn ich die Datei server.js ändere , wird der node.js-Server automatisch neu gestartet.
npm install nodemon --save-dev
Erstellen Sie nun im api -Ordner eine Datei namens 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);
});
Als Nächstes verbinden Sie die MongoDB-Datenbank mit unserer node.js-Anwendung.
Wenn Sie die MongoDB-Datenbank nicht installiert haben, installieren Sie sie und starten Sie den MongoDB-Server.
Geben Sie den folgenden Befehl ein, um den MongoDB -Server zu starten.
mongod
Also, jetzt habe ich mich mit der Datenbank verbunden.
Erstellen Sie eine Datei mit dem Namen DB.js im API -Root-Projektordner. Schreiben Sie dann den folgenden Code in die Datei DB.js.
// DB.js
module.exports = {
DB: 'mongodb://localhost:27017/ng7crud'
};
Importieren Sie diese DB.js -Datei in unsere server.js -Datei und verwenden Sie die Mongoose-Bibliothek , um die Datenbankverbindung mit MongoDB einzurichten . Wir können Mongoose auch verwenden, um die Daten mit Mongoose ORM in der Datenbank zu speichern.
Schreiben Sie den folgenden Code in die Datei server.js , um unsere MongoDB - Anwendung mit dem Node.js -Server zu verbinden.
// 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);
});
Speichern Sie die Datei und gehen Sie zum Terminal und starten Sie den Knotenserver.
nodemon server
Im Moment laufen also drei Server.
Denken Sie daran, dass alle drei Server ohne Fehler laufen; Andernfalls funktioniert unsere Anwendung nicht.
Wir müssen zwei Ordner im API -Stammordner mit den Namen routen und models erstellen .
Erstellen Sie im Ordner der Modelle ein Modell namens 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);
Wir haben also unser Schema für die Business-Sammlung definiert. Wir haben drei Felder namens person_name, business_name, business_gst_number.
Erstellen Sie im Routenordner eine Datei namens business.route.js.
Schreiben Sie den CRUD-Code in die Datei 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;
Wir haben das Mungo-Modell verwendet, um die Datenbank zu speichern, zu aktualisieren und zu löschen. Mongoose ist ein ORM , das in der MongoDB - Datenbank verwendet wird. Wir haben alle CRUD-Operationen in der Routendatei eingerichtet; Wir müssen sie in die Datei server.js importieren .
Unsere endgültige server.js -Datei sieht also so aus.
// 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);
});
Wenn alle Server betriebsbereit sind, können Sie zum Browser gehen, die Formulardaten ausfüllen und das Unternehmen hinzufügen. Sie können so etwas auf Ihrem Bildschirm sehen, wenn Sie erfolgreich sind.
Jetzt können wir die Datenbank mit den folgenden Befehlen überprüfen.
Öffnen Sie zuerst die Mongo-Shell auf dem 4. Tab, da alle anderen drei Tabs im Moment belegt sind.
mongo
Hier können wir sehen, dass die Werte in der MongoDB-Datenbank gespeichert sind. Ja!! Es ist uns gelungen.
Jetzt sind die verbleibenden Operationen Lesen, Aktualisieren und Löschen.
Schreiben Sie in die gst-get.component.html- Datei den folgenden Code.
<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>
Jetzt müssen wir in der Datei business.service.ts die Funktion schreiben, die die Geschäftsdaten aus der MongoDB - Datenbank abruft und sie in der Angular-Anwendung anzeigt .
// business.service.ts
getBusinesses() {
return this
.http
.get(`${this.uri}`);
}
Wir müssen diese business.service.ts -Datei und die Business.ts - Datei in die gst-get.component.ts- Datei aufnehmen.
Schreiben Sie den folgenden Code in die Datei 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;
});
}
}
Speichern Sie die Datei, gehen Sie zum Browser und wechseln Sie zu dieser URL: http://localhost:4200/business. Sie können die Liste der Unternehmen sehen.
Okay, zuerst müssen wir die Daten mit _id wise aus der MongoDB-Datenbank abrufen und diese Daten in der Datei gst-edit.component.html anzeigen .
Schreiben Sie also zuerst den folgenden Code in die Datei 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;
});
});
}
}
Hier wird beim Rendern der gst-edit-Komponente.ts die ngOnInit - Methode aufgerufen und eine HTTP-Anforderung an den Knotenserver gesendet und die Daten von einer _id abgerufen , um sie in der gst-edit.component.html- Datei anzuzeigen.
Jetzt müssen wir in der Datei business.service.ts die Funktion editBusiness codieren , um eine HTTP-Anforderung zu senden.
// 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}`);
}
}
Schließlich müssen wir das Formular in die Datei gst-edit.component.html schreiben .
<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>
Speichern Sie die Datei, gehen Sie zur Auflistungsseite, klicken Sie auf die Schaltfläche „Bearbeiten“ und sehen Sie sich das ausgefüllte Formular aus der Datenbank an.
Sie können die Warnung auch wie folgt sehen. Ignorieren Sie dieses Demo-Tutorial.
forms.js:1193 Anscheinend
verwenden Sie ngModel für dasselbe Formularfeld wie formControlName.
Die Unterstützung für die Verwendung der ngModel-Eingabeeigenschaft und des ngModelChange-Ereignisses mit
reaktiven Formulardirektiven wurde in Angular v6 eingestellt und
in Angular v7 entfernt.
Aktualisieren Sie nun die Daten. In die Datei business.service.ts müssen wir die Funktion schreiben, die die Daten aktualisiert.
// 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'));
}
Okay, schreiben Sie jetzt die Funktion updateBusiness() in die Datei 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']);
});
Speichern Sie die Datei, und Sie können die Daten aktualisieren.
Wenn Sie also keinen Fehler auf der Konsole finden, können Sie die Daten erfolgreich aktualisieren.
Ich habe bereits einen Bearbeitungs- und Aktualisierungsdienst geschrieben , um API-Aufrufe durchzuführen. Bis jetzt ist Erstellen, Lesen, Aktualisieren dieses Angular-CRUD-Beispiels abgeschlossen . Sehen Sie sich jetzt Delete an .
Wir müssen das Klickereignis auf der Schaltfläche „Löschen “ in der Datei „gst-get.component.html “ definieren .
<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>
Schreiben Sie nun die Funktion deleteBusiness in die Datei gst-get.component.ts .
// gst-get.component.ts
deleteBusiness(id) {
this.bs.deleteBusiness(id).subscribe(res => {
console.log('Deleted');
});
}
Erstellen Sie abschließend die Funktion deleteBusiness() in der Datei business.service.ts .
// business.service.ts
deleteBusiness(id) {
return this
.http
.get(`${this.uri}/delete/${id}`);
}
Schließlich habe ich die Löschfunktion abgeschlossen.
In diesem Tutorial haben wir also die CRUD-Funktionalität in Angular abgeschlossen.
1646478892
Angular CRUD significa una aplicación que consiste en crear, leer, actualizar y eliminar funcionalidades de datos. Es la guía completa sobre la creación de aplicaciones web CRUD (crear, leer, actualizar, eliminar) utilizando el nuevo marco angular. Angular acaba de ser lanzado y viene con algunas características nuevas y mejoras.
Primero, instalaremos Angular usando Angular CLI, y luego continuaremos desarrollando el frontend y el backend.
Si tiene una versión anterior de @angular/cli, puede ejecutar el siguiente comando para instalar las últimas versiones.
npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli
Si tiene algún problema, consulte mi Cómo actualizar Angular CLI a la versión 7 . Le ayudará a actualizar su Angular CLI y creará un nuevo proyecto Angular Seven.
Bien, ahora, si escribe el siguiente comando, puede ver que hemos actualizado Angular CLI.
Ahora, creará un nuevo proyecto Angular usando el siguiente comando.
ng new angular7crud
cd angular7crud
Después de ingresar a la carpeta del proyecto, abra el proyecto en Visual Studio Code usando el siguiente comando. Si no lo estás usando, entonces comienza a usarlo. Es el mejor editor para el desarrollo de Javascript .
code .
En el momento de la instalación, hemos habilitado el enrutamiento para nuestra aplicación. Es nuevo en Angular porque nos avisará mientras instalamos el repetitivo angular. Puede verificar el archivo llamado app-routing.module.ts dentro del directorio src >> app .
A continuación, instale Bootstrap 4 CSS Framework usando el siguiente comando.
npm install bootstrap --save
Ahora, agréguelo dentro del archivo angular.json .
"styles": [
"src/styles.css",
"./node_modules/bootstrap/dist/css/bootstrap.min.css"
],
Entonces, ahora podemos usar las clases de Bootstrap 4 en nuestro proyecto.
Inicie el servidor de desarrollo de Angular con el siguiente comando.
ng serve -o
Crearemos un proyecto en el que los usuarios puedan ingresar su nombre de usuario , nombre comercial y número de GST desde el formulario y enviarlo. Si los valores son incorrectos, se validarán en la interfaz y el formulario no se enviará. Por otro lado, si todos los valores parecen perfectos, enviaremos el formulario a la API backend , almacenando los valores dentro de la base de datos de MongoDB .
Ahora, crearemos algunos componentes angulares para hacer el trabajo.
Escriba el siguiente comando para generar componentes angulares . Realizaremos operaciones de creación, lectura y actualización. Entonces crearemos tres componentes.
ng g c gst-add --spec=false
ng g c gst-get --spec=false
ng g c gst-edit --spec=false
Los tres componentes se registran automáticamente dentro de un archivo app.module.ts . Necesitamos configurar el enrutamiento de componentes angulares dentro de un archivo 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 { }
Ahora, puede ver dentro del archivo app.component.html que la directiva <router-outlet> está ahí. Esta directiva nos ayuda a representar los diferentes componentes en función de la ruta URI.
Escriba el siguiente código dentro del archivo 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>
Guarde el archivo y vaya al navegador y haga clic en dos enlaces. Puede ver que podemos ver los diferentes componentes en función de la navegación.
Escriba el siguiente comando para instalar la biblioteca ng2-slim-loading-bar .
npm install ng2-slim-loading-bar --save
Entonces, si instala paquetes de terceros en este momento, no es compatible con Angular . Para cerrar la brecha entre Angular y los paquetes de terceros, necesitamos instalar la siguiente biblioteca. Eso es.
npm install rxjs-compat --save
Ahora, importe SlimLoadingBarModule dentro del archivo app.module.ts .
// app.module.ts
import { SlimLoadingBarModule } from 'ng2-slim-loading-bar';
imports: [
...
SlimLoadingBarModule
],
El siguiente paso es incluir el estilo con la biblioteca dentro del archivo src >> styles.css .
@import "../node_modules/ng2-slim-loading-bar/style.css";
Angular RouterModule nos da los siguientes módulos de eventos.
Ahora, escriba el siguiente código dentro del archivo 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();
}
}
}
Está haciendo que intercepte el evento de enrutamiento y agregue el componente de barra de carga a cada ruta para que podamos ver la indicación de enrutamiento cada vez que cambiamos las rutas.
El cambio final para mostrar el indicador de enrutamiento es agregar la directiva ng2-slim-loading-bar dentro del archivo app.component.html en la parte superior de la página.
<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>
Guarde el archivo y vaya a la terminal para ver si hay un error y si no, vaya al navegador y cambie las rutas, y puede ver que ahora podemos ver el indicador de enrutamiento.
Dentro del archivo gst-add.component.html , agregue el siguiente formulario de arranque 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>
Usaremos ReactiveFormsModule . Entonces, si es nuevo en Validación de formularios angulares , consulte mi artículo Validación de formularios angulares en este blog.
Ahora, importe ReactiveFormsModule dentro del archivo app.module.ts .
// app.module.ts
import { ReactiveFormsModule } from '@angular/forms';
imports: [
...
ReactiveFormsModule
],
Ahora, necesitamos escribir el código para el archivo app.component.ts . Recuerde, este no es un formulario basado en plantillas. Así que cambiaremos el código dentro del archivo app.component.ts .
Primero, importamos los módulos FormGroup, FormBuilder, Validators desde @angular/forms .
Además, cree un constructor y cree una instancia de FormBuilder .
Así que escriba el siguiente código dentro del archivo 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() {
}
}
Hemos utilizado el generador de formularios para manejar toda la validación. Entonces, en ese constructor, estamos creando un formulario con las reglas de validación. En nuestro ejemplo, hay tres campos. Si el texto de entrada está vacío, dará un error y debemos mostrarlo.
Ahora, escribe el siguiente código dentro del archivo 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>
Guarde el archivo y vaya al navegador, y puede ver si no pone ningún valor dentro del cuadro de entrada, verá los errores.
Importe HttpClientModule dentro del archivo app.module.ts .
// app.module.ts
import { HttpClientModule } from '@angular/common/http';
imports: [
...
HttpClientModule
],
Dentro de la carpeta de la aplicación src >> , cree un archivo llamado Business.ts y agregue el siguiente código.
// Business.ts
export default class Business {
person_name: String;
business_name: String;
business_gst_number: Number;
}
Escriba el siguiente comando para generar el archivo de servicio.
ng g service business --spec=false
Entonces, su archivo principal business.service.ts se ve así.
// business.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class BusinessService {
constructor() { }
}
Ahora, importe el archivo business.service.ts al archivo app.module.ts .
// app.module.ts
import { BusinessService } from './business.service';
providers: [ BusinessService ],
Necesitamos escribir el código que enviará la solicitud HTTP POST con los datos al servidor Node.js y guardar los datos en la base de datos MongoDB .
Escriba el siguiente código dentro del archivo 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'));
}
}
Hemos definido nuestra URL de API de backend, pero aún no hemos creado ningún backend, pero lo haremos en un par de pasos.
Necesitamos agregar el evento de clic al botón Agregar negocio. Así que agregue el siguiente código dentro del archivo 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>
Entonces, cuando no hay errores, podemos enviar el formulario y llamará a la función addBusiness del componente . Desde allí, llamaremos al servicio angular y el servicio enviará la solicitud HTTP Post al servidor Node.js.
Ahora, agregue la función addBusiness dentro del archivo gst-add.component.ts . Así que escriba el siguiente código dentro del archivo 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() {
}
}
Aquí, hemos definido la función y también importamos el archivo business.service.ts . A continuación, cree una instancia del objeto dentro del constructor y llame a la función del archivo businsess.service.ts .
Ya codificamos la función addBusiness dentro del archivo business.service.ts . Ahora, necesitamos configurar la API de backend.
Dentro de la carpeta raíz angular, cree una carpeta llamada api y vaya dentro de esa carpeta. Recuerde, será un proyecto completamente separado de Angular. Entonces sus node_modules son diferentes de un Angular .
Abra la terminal dentro de la carpeta api y escriba el siguiente comando.
npm init -y
Instale los siguientes módulos específicos del nodo.
npm install --save express body-parser cors mongoose
No reinicio el servidor de nodos cada vez; Cambio el archivo. Así que estoy instalando el servidor nodemon. Lo que hace es que cuando modifico el archivo server.js , reinicia el servidor node.js automáticamente.
npm install nodemon --save-dev
Ahora, dentro de la carpeta api , cree un archivo llamado 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);
});
Lo siguiente es conectar la base de datos MongoDB con nuestra aplicación node.js.
Si no ha instalado la base de datos MongoDB, instálela e inicie el servidor mongodb.
Escriba el siguiente comando para iniciar el servidor MongoDB .
mongod
Entonces, ahora, me he conectado a la base de datos.
Cree un archivo llamado DB.js dentro de la carpeta del proyecto raíz de API . Luego, escriba el siguiente código dentro del archivo DB.js.
// DB.js
module.exports = {
DB: 'mongodb://localhost:27017/ng7crud'
};
Importe este archivo DB.js dentro de nuestro archivo server.js y use la biblioteca mongoose para configurar la conexión de la base de datos con MongoDB . También podemos usar Mongoose para guardar los datos en la base de datos usando Mongoose ORM.
Escriba el siguiente código dentro del archivo server.js para conectar nuestra aplicación MongoDB al servidor 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);
});
Guarde el archivo y vaya a la terminal e inicie el servidor de nodos.
nodemon server
Entonces, en este momento, tiene tres servidores en ejecución.
Recuerde, los tres servidores funcionan bien sin ningún error; de lo contrario, nuestra aplicación no funcionará.
Necesitamos crear dos carpetas dentro de la carpeta raíz de api llamadas rutas y modelos .
En la carpeta de modelos , cree un modelo llamado 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);
Entonces, hemos definido nuestro esquema para la colección de negocios. Tenemos tres campos llamados person_name, business_name, business_gst_number.
En la carpeta de rutas , cree un archivo llamado business.route.js.
Escriba el código CRUD dentro del archivo 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;
Hemos utilizado el modelo mangosta para guardar, actualizar y eliminar la base de datos. Mongoose es un ORM utilizado en la base de datos MongoDB . Tenemos todas las operaciones CRUD configuradas en el archivo de ruta; necesitamos importarlos dentro del archivo server.js .
Entonces, nuestro archivo server.js final se ve así.
// 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);
});
Si todos los servidores están en funcionamiento, puede ir al navegador, completar los datos del formulario y agregar el negocio. Puede ver algo como esto en su pantalla si tiene éxito.
Ahora, podemos verificar la base de datos usando los siguientes comandos.
Primero, abra el shell de mongo en la cuarta pestaña porque las otras tres pestañas están ocupadas en este momento.
mongo
Aquí, podemos ver que los valores se almacenan en la base de datos MongoDB. ¡¡Sí!! Hemos tenido éxito.
Ahora, las operaciones restantes son Leer, Actualizar y Eliminar.
En el archivo gst-get.component.html , escriba el siguiente código.
<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>
Ahora, dentro del archivo business.service.ts , necesitamos escribir la función que obtiene los datos comerciales de la base de datos MongoDB y los muestra en la aplicación Angular .
// business.service.ts
getBusinesses() {
return this
.http
.get(`${this.uri}`);
}
Necesitamos incluir este archivo business.service.ts y el archivo Business.ts dentro del archivo gst-get.component.ts .
Escriba el siguiente código dentro del archivo 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;
});
}
}
Guarde el archivo, vaya al navegador y cambie a esta URL: http://localhost:4200/business. Puedes ver el listado de las empresas.
Bien, primero, necesitamos obtener los datos de la base de datos MongoDB usando _id wise y mostrar esos datos en el archivo gst-edit.component.html .
Primero, escriba el siguiente código dentro del archivo 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;
});
});
}
}
Aquí, cuando el componente gst-edit.ts se procesa , llamará al método ngOnInit y enviará una solicitud HTTP al servidor del nodo y obtendrá los datos de un _id para mostrarlos dentro del archivo gst-edit.component.html .
Ahora, dentro del archivo business.service.ts , necesitamos codificar la función editBusiness para enviar una solicitud 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}`);
}
}
Finalmente, necesitamos escribir el formulario dentro del archivo 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>
Guarde el archivo, vaya a la página de listado, haga clic en el botón editar y vea el formulario completo de la base de datos.
También puede ver la advertencia como la siguiente. Ignora este tutorial de demostración.
forms.js:1193
Parece que está usando ngModel en el mismo campo de formulario que formControlName.
La compatibilidad con el uso de la propiedad de entrada ngModel y el evento ngModelChange con
directivas de formulario reactivo quedó obsoleta en Angular v6 y se eliminó
en Angular v7.
Ahora, actualice los datos. Dentro del archivo business.service.ts , necesitamos escribir la función que actualiza los datos.
// 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'));
}
Bien, ahora escribe la función updateBusiness() dentro del archivo 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']);
});
Guarde el archivo y podrá actualizar los datos.
Entonces, si no encuentra ningún error en la consola, puede actualizar los datos con éxito.
Ya he escrito un servicio de edición y actualización para hacer llamadas a la API. Entonces, hasta ahora, Crear, Leer, Actualizar está completo de este ejemplo de Angular CRUD . Ahora, eche un vistazo a Eliminar .
Necesitamos definir el evento de clic en el botón Eliminar dentro del archivo 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>
Ahora, escriba la función deleteBusiness dentro del archivo gst-get.component.ts .
// gst-get.component.ts
deleteBusiness(id) {
this.bs.deleteBusiness(id).subscribe(res => {
console.log('Deleted');
});
}
Finalmente, cree la función deleteBusiness() dentro del archivo business.service.ts .
// business.service.ts
deleteBusiness(id) {
return this
.http
.get(`${this.uri}/delete/${id}`);
}
Finalmente, completé la funcionalidad de eliminación.
Entonces, en este tutorial, hemos completado la funcionalidad CRUD en Angular.