Skip to content

Instantly share code, notes, and snippets.

@Fedko
Forked from andreykko/instruction.md
Last active January 30, 2019 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fedko/a2949afa5278e4997c66995377ede6ae to your computer and use it in GitHub Desktop.
Save Fedko/a2949afa5278e4997c66995377ede6ae to your computer and use it in GitHub Desktop.
Інструкція зі запуску застосунку

Частина 1. Загальна конфігурація.

  1. Встановлюємо angular-cli глобально: npm install -g @angular/cli
  2. Створюємо новий проект (--routing дозволяє створити проект відразу зі спеціальним Route модулем): ng new jsexpert-chat-bot --routing
  3. Заходимо в теку: cd jsexpert-chat-bot
  4. Запускаємо сервер: ng serve
  5. Якщо необхідно запустити в «продакшен» режимі: ng serve --prod
  6. Відкриваємо сторінку: http://localhost:4200 (переконуємося, що порожній проект запущений і працює)
  7. Зупиняємо проект: ctrl+c
  8. Створюємо новий модуль: ng generate module angular-bot --spec=false
  9. Створюємо новий компонент main: ng generate component angular-bot/main --spec=false
  10. Створюємо новий компонент 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

<h2>Вас вітає застосунок Angular Bot</h2><br>
<h3>Перейдіть в пункт меню чат для початку спілкування</h3>

Створимо сервіс 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 = {
    "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