使用typescript開發(fā)angular模塊(編寫模塊)

前言

之前在使用typescript開發(fā)angular模塊(發(fā)布npm包)一文中基本掌握了怎么發(fā)布一個typescript寫的npm包。但是離目標(biāo)還有段距離酷鸦。

開始開發(fā)模塊

開發(fā)過程不是自己想了那么順利荆责,但是還是有點(diǎn)可取的地方滥比。

安裝依賴項目

  "dependencies": {
    "@angular/common": "^5.0.2",
    "@angular/core": "^5.0.2",
    "moment": "^2.22.1",
    "rxjs": "^5.5.2",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@types/core-js": "^0.9.35",
    "typescript": "^2.8.1",
    "typings": "^2.1.1"
  }

配置tsconfig.json文件

{
  "compilerOptions": {
    /* Basic Options */
    "typeRoots": [                 // 主要配置了這個
      "node_modules/@types"
    ],
    "lib": [                // 還有這個
      "es2017",
      "dom"
    ],
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
    //"module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */

    /* Source Map Options */
    // "sourceRoot": "./",                    /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "./",                       /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    "emitDecoratorMetadata": true         /* Enables experimental support for emitting type metadata for decorators. */
  }
}

編寫代碼

像寫普通的angular模塊一樣


image.png

index.ts

import { NgModule } from '@angular/core';
import {CommonModule} from "@angular/common";
import {BlogApiService} from "./provider";

@NgModule({
    imports: [
        CommonModule
    ],
    providers:    [ BlogApiService ],
})
export class MzcNgApiModule { }

發(fā)布使用

似乎哪里沒有配置正確,引入MzcNgApiModule 來使用時編譯要報錯做院。但是引入BlogApiService使用卻很正常

在我們的angular項目中安裝

npm i mzc-ng-api

能正常使用的情況如下

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BlogApiService} from  "mzc-ng-api/src/provider"
export * from "mzc-ng-api/src/provider"

@Injectable()
export class BlogService extends BlogApiService{
  constructor(protected http: HttpClient) {
    super(http)
  }
}

編譯通過盲泛,在下面的地方能正確調(diào)用BlogApiService里的方法

import {BlogService, PreNoteDto,GetNoteDto} from "../blog.service";

export class NoteListComponent implements OnInit {
  preNoteList:PreNoteDto[]=[];
  loadMore = false;
  loading =false;
  key="";

  constructor(private router: Router,
  private blogService :BlogService
  ) { }

  ngOnInit() {
    this.getNoteList(true);
  }
  getNoteList(f=false){
    this.loading= true;
    if(f)this.preNoteList =[];
    const param = new GetNoteDto();
    param.key = this.key;
    param.SkipCount = this.preNoteList.length;
    this.blogService.GetNoteList(param).do(()=>{
      this.loading = false;
    }).subscribe(m=> {
      m.items.forEach((v,i)=>{
        v.content = marked(v.content);
        this.preNoteList.push(v);
      });
      this.loadMore = m.totalCount>this.preNoteList.length;
    });
  }
}

不能正常使用的方法如下

在app.module.ts中

import {MzcNgApiModule} from 'mzc-ng-api'

  imports: [
    RouterModule,
    MzcNgApiModule,
    BrowserModule,
    NgZorroAntdModule.forRoot(),
    RoutesModule,
    BrowserAnimationsModule
  ],

這樣引入進(jìn)來濒持,還沒有使用編譯都會報錯。錯誤內(nèi)容幾乎也時看不明白寺滚,先記錄下來柑营,日后慢慢解決。


image.png

未完待續(xù)

源碼地址

https://github.com/yiershan/MZC-Ng-Api

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末村视,一起剝皮案震驚了整個濱河市官套,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌蚁孔,老刑警劉巖奶赔,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異杠氢,居然都是意外死亡站刑,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進(jìn)店門鼻百,熙熙樓的掌柜王于貴愁眉苦臉地迎上來绞旅,“玉大人,你說我怎么就攤上這事愕宋〔C遥” “怎么了?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵中贝,是天一觀的道長囤捻。 經(jīng)常有香客問我,道長邻寿,這世上最難降的妖魔是什么蝎土? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮绣否,結(jié)果婚禮上誊涯,老公的妹妹穿的比我還像新娘。我一直安慰自己蒜撮,他們只是感情好暴构,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著段磨,像睡著了一般取逾。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上苹支,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天砾隅,我揣著相機(jī)與錄音,去河邊找鬼债蜜。 笑死晴埂,一個胖子當(dāng)著我的面吹牛究反,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播儒洛,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼精耐,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了琅锻?” 一聲冷哼從身側(cè)響起黍氮,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎浅浮,沒想到半個月后沫浆,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡滚秩,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年专执,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片郁油。...
    茶點(diǎn)故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡本股,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出桐腌,到底是詐尸還是另有隱情拄显,我是刑警寧澤,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布案站,位于F島的核電站躬审,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏蟆盐。R本人自食惡果不足惜承边,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望石挂。 院中可真熱鬧博助,春花似錦、人聲如沸痹愚。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽拯腮。三九已至窖式,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間疾瓮,已是汗流浹背脖镀。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工飒箭, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留狼电,地道東北人蜒灰。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像肩碟,于是被迫代替她去往敵國和親强窖。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,843評論 2 354

推薦閱讀更多精彩內(nèi)容