Устанавливаем angular-cli глобально
npm install -g @angular/cli
Создаем новый проект (--routing позволяет создать проект сразу с специальным Route модулем)ng new jsexpert-chat-bot --routing
Заходим в папкуcd jsexpert-chat-bot
Запускаем серверng serve
Если необходимо запустить в "продакшен" режимеng serve --prod
Открываем страницу ⁃ http://localhost:4200 (убеждаемся что пустой проект запущен и работает) Останавливаем проектctrl+c
Создаем новый модульng generate module angular-bot --spec=false
Создаем новый компонент mainng generate component angular-bot/main --spec=false
Создаем новый компонент chatng generate component angular-bot/chat --spec=false
Часть 2. Настройка AppModule и Routes Подключим AngularBotModule модуль в AppModule (в файле app.module.ts)
import { AngularBotModule } from './angular-bot/angular-bot.module';
imports: [
BrowserModule,
AppRoutingModule,
AngularBotModule
]
Подключим в index.html необходимые стили
<link rel="stylesheet" href="//cdn.rawgit.com/necolas/normalize.css/master/normalize.css">
<link rel="stylesheet" href="//cdn.rawgit.com/milligram/milligram/master/dist/milligram.min.css">
Добавим логику для навигации в app.component.ts
links = [
{ path: '/main', label: 'Главная', active: 'button-active'},
{ path: '/chat', label: 'Чат', active: 'button-active'}
];
Добавим стили в app.component.css
.button {
margin-right: 20px
}
.button-active {
background-color: #9b4dca;
color: white;
}
.button-active:hover,
.button-active:focus {
background-color: #9b4dca;
border-color: #9b4dca;
color: #fff;
}
.top-bar {
margin: 25px 0;
}
Добавим верстку в app.component.html
<div class="row top-bar">
<div class="column column-25"></div>
<div class="column column-50">
<button class="button button-outline"
*ngFor="let topLink of links"
[routerLink]="topLink.path"
[routerLinkActive]="topLink.active">
{{topLink.label}}
</button>
</div>
</div>
<div class="row">
<div class="column"></div>
<div class="column column-50">
<router-outlet></router-outlet>
</div>
<div class="column"></div>
</div>
Добавим настройку маршрутов в app-routing.module.ts
const routes: Routes = [
{ path: "", pathMatch: "full", redirectTo: "main" },
{ path: "main", component: MainComponent },
{ path: "chat", component: ChatComponent}
];
Запустить проект и убедиться в том что маршруты работают
- ng serve Часть 3. Реализация логики чата Добавим текст в main.component.html
Создадим сервис chat.service.ts ng generate service angular-bot/chat --spec=false
Подключим его в angular-bot.module.ts providers: [ChatService] Реализуем функционал в chat.service.ts
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
export class Message {
constructor(public author: string, public content: string) {}
}
@Injectable()
export class ChatService {
constructor() {}
conversation = new Subject<Message[]>();
messageMap = {
"Привет": "Приветвствую вас",
"Кто ты такой?": "Я Ангуляр бот, что вы хотите узнать",
"Когда будет следующий курс?": "Следующий курс начинается 22 мая, приходите",
"Спасибо": "Пожалуйста, всегда готов помочь",
"Hi": "Hello",
"Who are you": "My name is Agular Bot",
"What is Angular": "Angular is the best framework ever",
"default": "I can't understand. Can you please repeat"
}
getBotAnswer(msg: string) {
const userMessage = new Message('user', msg);
this.conversation.next([userMessage]);
const botMessage = new Message('bot', this.getBotMessage(msg));
setTimeout(()=>{
this.conversation.next([botMessage]);
}, 1500);
}
getBotMessage(question: string){
let answer = this.messageMap[question];
return answer || this.messageMap['default'];
}
}
Добавим стили в chat.component.css
.message {
border-radius: 50px;
margin: 0 15px 20px;
padding: 10px 20px;
position: relative;
font-size: 20px;
}
.message.to {
background-color: #2095FE;
color: #fff;
margin-left: 100px;
text-align: right;
}
.message.from {
background-color: #E5E4E9;
color: #363636;
margin-right: 100px;
}
.message.to + .message.to,
.message.from + .message.from {
margin-top: -10px;
}
Добавить логику в chat.component.ts
messages: Message[] = [];
value: string;
constructor(public chatService: ChatService) { }
ngOnInit() {
this.chatService.conversation.subscribe((val) => {
this.messages = this.messages.concat(val);
});
}
sendMessage() {
this.chatService.getBotAnswer(this.value);
this.value = '';
}
Добавить верстку в chat.component.html
<h1>JSExpert Angular Chat Bot</h1>
<ng-container *ngFor="let message of messages">
<div class="message"
[ngClass]="{ 'from': message.author === 'bot',
'to': message.author === 'user' }">
{{ message.content }}
</div>
</ng-container>
<label *ngIf="messages.length == 0; else dialogInfo" for="nameField">Ваше сообщение</label>
<input [(ngModel)]="value" (keyup.enter)="sendMessage()" type="text">
<button (click)="sendMessage()">Отправить</button>
<ng-template #dialogInfo>
<span [className]="'float-right'">Всего сообщений: {{messages.length}}</span>
</ng-template>
Добавить FormsModule в AngularBotModule
import { FormsModule } from '@angular/forms';
imports: [
CommonModule,
FormsModule
]