iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 26
0
Modern Web

從零開始的Angular前端開發系列 第 26

# DAY 26 整合架構

DAY 26 整合

今天來總整理一下全部的程式碼吧

首先為登入和註冊的表單,套上CSS,讓他看起來美觀一點:

// register.component.css
// login.component.css
form {
  margin: auto;
  width: 25%;
  border: 5px solid #619c66;
  padding: 20px;
}

input[type=text],[type=password] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  box-sizing: border-box;
  position: relative;

}
input[type=button], input[type=submit], input[type=reset] {
  background-color: #50bb59;
  border: none;
  color: white;
  padding: 16px 32px;
  text-decoration: none;
  margin: 4px 2px;
  cursor: pointer;
  width: 100%;
}

// login.component.html

  <form  class="form" #f="ngForm" (ngSubmit)="onSubmit()" >
    <input type="text" [(ngModel)]="account.email" name="username" placeholder="E-mail"><br>
    <input type="password" [(ngModel)]="account.password" name=password placeholder="Password"><br>
    <input type="submit" value="Login">
  </form>

原本的 Login 表單就會長成像這樣:

接下來把 API的部分接好:

// http.service.ts

  Register(data) {
    this.http.post('/api/user/new', data).subscribe(
      (result) => {
        console.log(result);
        this.data = result;
      },
      (error) => {
        console.log(error);
      }
    );

  }
  login(data) {
    this.http.post('/api/user/login', data).subscribe(
      (result) => {
        console.log(result);
        this.data = result;
      },
      (error) => {
        console.log(error);

      }
    );
 // login.component.ts
 
  onSubmit() {
    this.http.login(this.account);
  }
  

確定可以登入:

接下來會遇到一個問題,登入成功後,我要怎麼把登入的狀態,送到 Navigation-bar,去改變 islogin 的狀態呢?

或是說,我們如果想要在 Component 裡面拿回 API 的結果,要怎麼做呢?

我們的程式碼可以改成這樣:

 // login.component.ts

import 'rxjs';
import { Observable } from 'rxjs';

  response$: Observable<any>;
  status;
  
  onSubmit() {
    this.response$ = this.http.login(this.account);
    this.response$.subscribe(
      (result => {
        this.status = result.status;
        alert(this.status);
      })
    );

 // http.service.ts
 
import { Observable } from 'rxjs';
 
  login(data): Observable<any> {
    return this.http.post('/api/user/login', data);
  }

這樣就能在 Component 裡去處理回傳的訊息。你看到這邊用到了之前一直沒有提到的 RxJSObservable 物件。那麼要讓 Navigation-bar 知道我們已經登入成功,就要使用到 RxJS 了,我們明天來繼續處理非同步以及訂閱的問題。


上一篇
# DAY 25 Routing (三)
下一篇
# DAY 27 部署 & 執行
系列文
從零開始的Angular前端開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言