Skip to content

Instantly share code, notes, and snippets.

@andreykko
Last active January 30, 2019 19:56
Show Gist options
  • Save andreykko/5a2b164ed24e23ba3dc930279ffd8060 to your computer and use it in GitHub Desktop.
Save andreykko/5a2b164ed24e23ba3dc930279ffd8060 to your computer and use it in GitHub Desktop.
Частина 1. Загальна конфігурація.

Устанавливаем 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 Создаем новый компонент main
  • ng generate component angular-bot/main --spec=false Создаем новый компонент chat
  • ng 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

Вас приветсвует приложение Angular Bot


Перейдите в пункт меню чат для начала общения

Создадим сервис 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
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment