1. 程式人生 > >從flask視角學習angular

從flask視角學習angular

sele ref lar logs tar rdquo mode 理解 sel

前端框架完全不懂。

看著angular中文官網的英雄編輯器教程和核心知識,用偷懶的類比法,從flask django的角度 記錄一下自己對angular的理解.

app.module.ts

這個文件有點類似extends.py 在這裏import各種依賴的插件。比如要雙向綁定,就要import FormsModule

import { NgModule }      from ‘@angular/core‘;
import { BrowserModule } from ‘@angular/platform-browser‘;
import { FormsModule }   from 
‘@angular/forms‘; // <-- NgModel lives here import { AppComponent } from ‘./app.component‘; @NgModule({ imports: [ BrowserModule, FormsModule // <-- import the FormsModule before binding with [(ngModel)] ],

@ngModule 類Flask的app,其他的component類似blueprint。在這裏declarations裏添加其他的component,類似 註冊藍圖
import { NgModule }       from ‘@angular/core‘;
import { BrowserModule }  from 
‘@angular/platform-browser‘; import { FormsModule } from ‘@angular/forms‘; import { AppComponent } from ‘./app.component‘; import { DashboardComponent } from ‘./dashboard.component‘; import { HeroDetailComponent } from ‘./hero-detail.component‘; import { HeroesComponent } from ‘./heroes.component‘; import { HeroService } from
‘./hero.service‘; import { AppRoutingModule } from ‘./app-routing.module‘; @NgModule({ imports: [ BrowserModule, FormsModule, AppRoutingModule ], declarations: [ AppComponent, DashboardComponent, HeroDetailComponent, HeroesComponent ], providers: [ HeroService ], bootstrap: [ AppComponent ] }) export class AppModule { }

類似

from flask import Flask

from scenario import scenario
from situation import situation
from posture import posture
from assistant import assistant
from do_action import do_action
from rule import rule

# ————————註冊blueprint————————
app.register_blueprint(scenario)
app.register_blueprint(situation)
app.register_blueprint(posture)
app.register_blueprint(do_action)
app.register_blueprint(assistant)
app.register_blueprint(rule)

app = Flask(__name__)

app.component.ts

import { Component } from ‘@angular/core‘;

@Component({
  selector: ‘my-app‘,
  template: `
    <h1>{{title}}</h1>
    <nav>
      <a routerLink="/dashboard" routerLinkActive="active">Dashboard</a>
      <a routerLink="/heroes" routerLinkActive="active">Heroes</a>
    </nav>
    <router-outlet></router-outlet>
  `,
  styleUrls: [‘./app.component.css‘],
})
export class AppComponent {
  title = ‘Tour of Heroes‘;
}
@Component 相當於 flask裏

1 /templates/每個blueprint下的用 jinja2 語法的XXX.html,
2 /static/下的 css

區別在於:flask強調"動靜分離"。這樣部署的時候,static的東西用nginx, web api部分 用 gunicorn
angular 的component(有點類似Unity3d裏的gameobject),把css 模板 都封裝在了組件裏,寫在了代碼裏。
angular的“前後端”統統用ts/js搞了。這樣開發者不需要太在乎“動靜”與“前後"的分野。

Model部分

export class Hero {
  id: number;
  name: string;
}

類似 models.py定義的ORM類。可以送進模板用雙括號訪問屬性 {{hero.name}}

ng的雙向綁定很給力。

<div>
  <label>name: </label>
  <input [(ngModel)]="hero.name" placeholder="name">
</div>

從flask視角學習angular