Home php c# sql c c++ javascript python java go android git linux asp.net django .net node.js ios xcode cocoa iphone mysql tomcat mongodb bash objective-c scala visual-studio apache elasticsearch jar eclipse jquery ruby-on-rails ruby rubygems android-studio spring lua sqlite emacs ubuntu perl docker swift amazon-web-services svn html ajax xml java-ee maven intellij-idea rvm macos unix css ipad postgresql css3 json windows-server vue.js typescript oracle hibernate internet-explorer github tensorflow laravel symfony redis html5 google-app-engine nginx firefox sqlalchemy lucene erlang flask vim solr webview facebook zend-framework virtualenv nosql ide twitter safari flutter bundle phonegap centos Register | Login | Edit Tags | New Questions | 繁体 | 简体


10 questions online user: 21

0
votes
answers
12 views
+10

爲每個訂閱創建於掃描操作符的新種子對象

1

RxJS 5.5.2爲每個訂閱創建於掃描操作符的新種子對象

我有下面的代碼誰分裂的數字陣列爲對象,具有2個屬性「小」的數字越小則4和'大'其餘。

const o = from([1, 2, 3, 4, 5, 6]).pipe(
    scan<number, {}>((a, b) => { 
    if (b < 4) { 
     a['small'].push(b); 
    } else { 
     a['big'].push(b); 
    } 
    return a; 
    }, { 
    'small': [], 
    'big': [] 
    }) 
); 
console.log('subscription 1'); 
o.subscribe(x => console.log(JSON.stringify(x))); 
console.log('subscription 2'); 
o.subscribe(x => console.log(JSON.stringify(x))); 

認購1控制檯打印後:

{"small":[1,2,3],"big":[4,5,6]} // this is ok 

訂購2臺打印後:

{"small":[1,2,3,1,2,3],"big":[4,5,6,4,5,6]} // this is not ok 

有沒有開始一個新的種子對象每次有人贊同呢?

沙发
0
2

另一種選擇是將管道封裝在defer塊中,該塊將在訂閱時重建源流。

defer(() => 
    from([1, 2, 3, 4, 5, 6]).pipe(
    scan<number, {}>((a, b) => { 
     if (b < 4) { 
     a['small'].push(b); 
     } else { 
     a['big'].push(b); 
     } 
     return a; 
    }, { 
     'small': [], 
     'big': [] 
    }) 
) 
); 

每個訂閱都會調用推遲塊中的方法並訂閱結果。儘管像@arturgrzesiak提到的那樣,變異數組在函數式編程和擴展功能反應式編程中被看作反模式。

板凳
0
2

掃描累加器({ small: [], big: [] })被.push突變,這是一種反模式,可能很容易導致意外的行爲。防止改變先前發出的值

一種選擇可能是:

scan<number, {}>((a, b) => { 
    if (b < 4) { 
    return Object.assign({}, a, {small: a.small.concat([b])}); 
    } else { 
    return Object.assign({}, a, {big: a.big.concat([b])}); 
    } 
}, { 
    'small': [], 
    'big': [] 
}) 

不知道你正在試圖完成什麼,但它可能是值得看一看的partition運營商,這將產生兩個單獨的值流如const [small, big] = someStream.partition(x => x < 4);

+2

看來OP正在使用Typescript,所以你可以簡化使用ES7賦值符號'{... a,small:[... a.small,b]}' – paulpdaniels

+0

@paulpdaniels好點 –

0
votes
answers
8 views
+10

錯誤:未捕獲(承諾中):TypeError:無法讀取未定義的屬性「映射」

1

僅當它嘗試從catch返回值時,纔會發生以下錯誤。希望我在這裏做一個根本錯誤的事情。請給我一個線索。爲什麼我不能從catch返回observable錯誤:未捕獲(承諾中):TypeError:無法讀取未定義的屬性「映射」

.TS

getMyTopic() { 
    return this.topicSer.getMyTopics().map((res: any) => res.json()).map((res: any) => res = res.categories) 
     .catch((err: any) => { 
     console.log('err', err); 
     return [] 
     }) 
    }  

provider.ts

getMyTopics(): Observable<any> { 
     if (typeof this.userService.userDetails != 'undefined') { 
      this.localCacheService.getItem(this.localCacheService.discoverTopicsKey).then((val) => { 
     if (val != null && val.length == 0) return this.apiService.get(config.discover_topic_WITHAUTH); 
     }).catch(() => { 
     return this.apiService.get(config.discover_topic_WITHOUTAUTH);//here is the issue 
      }); 
     } 

錯誤

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'map' of undefined 
TypeError: Cannot read property 'map' of undefined 
    at Discover.webpackJsonp.402.Discover.getMyTopic (discover.ts:123) 
    at Discover.webpackJsonp.402.Discover.getData (discover.ts:69) 
    at discover.ts:51 
    at t.invoke (polyfills.js:3) 
    at Object.onInvoke (core.js:4626) 
    at t.invoke (polyfills.js:3) 
    at r.run (polyfills.js:3) 
    at polyfills.js:3 
    at t.invokeTask (polyfills.js:3) 
    at Object.onInvokeTask (core.js:4617) 
    at Discover.webpackJsonp.402.Discover.getMyTopic (discover.ts:123) 
    at Discover.webpackJsonp.402.Discover.getData (discover.ts:69) 
    at discover.ts:51 
    at t.invoke (polyfills.js:3) 
    at Object.onInvoke (core.js:4626) 
    at t.invoke (polyfills.js:3) 
    at r.run (polyfills.js:3) 
    at polyfills.js:3 
    at t.invokeTask (polyfills.js:3) 
    at Object.onInvokeTask (core.js:4617) 
    at c (polyfills.js:3) 
    at polyfills.js:3 
    at t.invokeTask (polyfills.js:3) 
    at Object.onInvokeTask (core.js:4617) 
    at t.invokeTask (polyfills.js:3) 
    at r.runTask (polyfills.js:3) 
    at o (polyfills.js:3) 
    at e.invokeTask [as invoke] (polyfills.js:3) 
    at p (polyfills.js:2) 
    at IDBRequest.v (polyfills.js:2) 
defaultErrorLogger @ core.js:1350 
ErrorHandler.handleError @ core.js:1411 
IonicErrorHandler.handleError @ ionic-error-handler.js:61 
next @ core.js:5373 
schedulerFn @ core.js:4220 
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238 
SafeSubscriber.next @ Subscriber.js:185 
Subscriber._next @ Subscriber.js:125 
Subscriber.next @ Subscriber.js:89 
Subject.next @ Subject.js:55 
EventEmitter.emit @ core.js:4200 
(anonymous) @ core.js:4648 
t.invoke @ polyfills.js:3 
r.run @ polyfills.js:3 
NgZone.runOutsideAngular @ core.js:4574 
onHandleError @ core.js:4648 
t.handleError @ polyfills.js:3 
r.runGuarded @ polyfills.js:3 
(anonymous) @ polyfills.js:3 
n.microtaskDrainDone @ polyfills.js:3 
o @ polyfills.js:3 
e.invokeTask @ polyfills.js:3 
p @ polyfills.js:2 
v @ polyfills.js:2 
IndexedDB (async) 
(anonymous) @ localforage.js:826 
t.invoke @ polyfills.js:3 
onInvoke @ core.js:4626 
t.invoke @ polyfills.js:3 
r.run @ polyfills.js:3 
(anonymous) @ polyfills.js:3 
t.invokeTask @ polyfills.js:3 
onInvokeTask @ core.js:4617 
t.invokeTask @ polyfills.js:3 
r.runTask @ polyfills.js:3 
o @ polyfills.js:3 
e.invokeTask @ polyfills.js:3 
p @ polyfills.js:2 
v @ polyfills.js:2 
沙发
0
0

getMyTopics方法不會返回任何內容。當catch運算符返回一個Observable時,它將返回一個空數組。

0
votes
answers
7 views
+10

打字稿,使用類沒有構造

17

雖然與「英雄之旅」教程中的角網站上的工作,我發現下面的語法(不久):打字稿,使用類沒有構造

class Hero { 
    id: number, 
    name: string, 
} 

const aHero: Hero = { 
    id: 1, 
    name: 'Superman' 
} 

console.log(aHero instanceof Hero); //false 

什麼會做這點?當我檢查「aHero」的類型時,它只是一個普通對象而不是「英雄」類型。用構造函數初始化一個對象會更好嗎?:

class Hero { 
    constructor(id: number, name: string) {} 
} 
+13

好問題。答案是教程促進了一種不好的做法。 '英雄'應該是一個'界面'。 –

+2

託德格言有一個[偉大的文章](https://toddmotto.com/classes-vs-interfaces-in-typescript)解釋差異和何時/爲什麼要使用'接口'與'類' – mhodges

+0

你可以添加一個引用到這個代碼的部分? –

沙发
0
2

您可以使用class作爲您使用它的方式。所以,無論Hero是接口還是類,它都不重要,因爲您將它用作類型。

class Hero { id: number; name: string } 

interface Hero { id: number; name: string } 

下列不擔心英雄是否是類或接口

let hero: Hero = { id: 1, name: 'me' } 

interfaceclass分辯interface是隻爲你,它不沒有得到JavaScript轉化。 A class確實如此,你不能newinterface

構造函數或沒有構造函數,如果你new那麼它就是instanceof。與此

let hero = new Hero(); 

instanceof日誌再次嘗試將true因爲你確實創造了英雄的一個實例用關鍵字new

0
votes
answers
7 views
+10

Array.prototype.filter和歧視聯盟的最小類型註釋?

1

考慮下面的代碼片段:Array.prototype.filter和歧視聯盟的最小類型註釋?

type asdf = '.' | number; 
const foo: asdf[] = ['.', 1, 3, '.']; 
const bar: number[] = foo.filter(v => typeof v === 'number'); 

它無法編譯,因爲編譯器無法推斷出的bar類型是number[]

  1. 爲什麼編譯器不能推導出正確的類型?
  2. 什麼是使編譯器理解類型的最小類型註釋?
沙发
0
1

您需要使用type guard來實現此目的。

一個類型後衛是一個函數,它接收一個項目v並聲明它是類型Foo。在你的榜樣,你的類型後衛看起來就像這樣:

function isNumber(value: asdf): value is number { 
    return typeof value === "number"; 
} 

然後,您將通過該值到您的filter功能,像這樣:

const bar: number[] = foo.filter(isNumber); 

如果你想保持你的函數內聯,你可以做這樣的(但我認爲這是一個有點不太清楚):

const bar: number[] = foo.filter((item): item is number => typeof item === "number"); 

你的代碼是行不通的,因爲你沒有足夠的item is number一部分 - 告訴合作mpiler,如果斷言(typeof item === "number")返回true,則item的類型爲number

+0

內聯版本**完全**是我希望的解決方案。非常感謝! – LudvigH

0
votes
answers
7 views
+10

Angular 5的HttpClient:toPromise()接受哪些參數?

0

如果我試圖返回一個特定類型的這樣一個承諾:Angular 5的HttpClient:toPromise()接受哪些參數?

public myMethod(): Promise<MyType> { 
    return this.httpClient.get('/my/url').toPromise(); 
} 

...我得到一個錯誤的返回類型無極<對象>不符合預期的類型無極<的MyType >。這是很容易通過將結果或通過這樣來解決:

public myMethod(): Promise<MyType> { 
    return this.httpClient.get<MyType>('/my/url').toPromise(); 
} 

還有另一種選擇,但是,爲了提供一個可選的參數給toPromise()函數。我的IDE說參數的類型是「PromiseCtor:PromiseConstructorLike」或「PromiseCtor:typeof Promise」。

public myMethod(): Promise<MyType> { 
    return this.httpClient.get('/my/url').toPromise(???); 
} 

我想不通什麼語法會滿足???上面,但是。

關於什麼可以作爲一個有效的參數在這裏填寫任何想法?

+0

我認爲這是要求輸入['Promise'構造(https://developer.mozilla.org/en-US/docs/網絡/ JavaScript的/參考/ Global_Objects /無極)。這可以是本地的,也可以是您最喜歡的承諾庫提供的。這不會幫助你用'MyType',順便說一句。 – Bergi

+0

假設您有特殊類型的承諾MyPromise,您可以傳遞該類型(即MyPromise的構造函數)。目標不是解決你的問題。目標也是返回一個特定類型的Promise。 –

沙发
0
0

您需要首先將返回數據映射到您的對象。

public myMethod(): Promise<MyType> { 
    return this.httpClient.get('/my/url') 
    .map(response => <MyType>response.json()) 
    .toPromise(); 
} 
+0

這看起來像你現在不推薦使用的HttpModule,而不是新的HttpClientModule。當我切換到HttpClientModule時,我從地圖代碼中取出了地圖功能,而且沒有它,我的代碼就可以正常工作。 – kshetline

板凳
0
0

你需要指定喜歡的類型:

`public myMethod(): Promise<MyType> { 
return this.httpClient.get<MyType>('/my/url').toPromise().then((res) => { 
// code goes here. 
}); 
}` 
0
votes
answers
6 views
+10

獲取$ key對象實時數據庫Firebase

-1

我正在基於每個對象的ID或$key實現Firebase實時數據庫中的動態路由。我想要的是獲得身份證,我無法找到方式,我得到的值爲undefinied。有任何想法嗎?

enter image description here

enter image description here

portafolio.component.html

<div class="container my-5"> 
<h1>Portafolio</h1> 
<div class="row"> 
    <div class="col-md-4" *ngFor="let proyecto of proyectos | async"> 
     <div class="card my-3"> 
      <div class="card-body"> 
       <h4 class="card-title">{{ proyecto.titulo }}</h4> 
       <a class="btn btn-primary" [routerLink]="['/portafolio', proyecto.$key]">Ver detalles</a> 
      </div> 
     </div> 
    </div> 
</div> 

portafolio.component.ts

import { Component, OnInit } from '@angular/core'; 
 
import { AngularFireDatabase, AngularFireList, AngularFireObject } from 'angularfire2/database'; 
 

 

 
@Component({ 
 
    selector: 'app-portafolio', 
 
    templateUrl: './portafolio.component.html', 
 
    styleUrls: ['./portafolio.component.scss'] 
 
}) 
 
export class PortafolioComponent implements OnInit { 
 

 
    proyectos: any; 
 

 
    constructor(private db: AngularFireDatabase) { } 
 

 
    ngOnInit() { 
 

 
     this.proyectos = this.db.list('proyectos').valueChanges(); 
 

 
    } 
 

 
}

proyecto.ts

export interface Proyecto { 
$key?: string; 
titulo?: string; 
destacado?: string; 
descripcion?: string;} 
+3

你需要使用'snapshotChanges爲了得到鍵。檢查此[回答](https://stackoverflow.com/questions/47291644/angular-firebase-5-objects-keys-not-being-displayed-so-cant-delete/47291970#47291970) – Hareesh

+0

優秀爲我工作與'snapshotChanges()' –

沙发
0
0

用方括號來訪問對象的屬性,proyecto['$key']

<a class="btn btn-primary" [routerLink]="['/portafolio', proyecto['$key']]">Ver detalles</a> 
+0

你確定嗎?我仍然出來'undefined' –

+0

post'' proyecto'對象 –

+0

我已經包含了項目project.ts –

板凳
0
0

感謝@Hareesh分享相關主題:https://stackoverflow.com/a/47291970/8312532

這爲我工作:

portafolio.component.ts

import { Component, OnInit } from '@angular/core'; 
 
import { AngularFireDatabase, AngularFireList} from 'angularfire2/database'; 
 
import { Observable } from "rxjs/Observable"; 
 

 

 

 
@Component({ 
 
    selector: 'app-portafolio', 
 
    templateUrl: './portafolio.component.html', 
 
    styleUrls: ['./portafolio.component.scss'] 
 
}) 
 
export class PortafolioComponent implements OnInit { 
 

 
    todosProyectos: AngularFireList<any>; 
 
    proyectos: Observable<any[]>; 
 

 
    constructor(private db: AngularFireDatabase) { } 
 

 
    ngOnInit() { 
 

 
    this. todosProyectos = this.db.list('proyectos'); 
 

 
    this.proyectos = this.todosProyectos.snapshotChanges().map(changes => { 
 
     return changes.map(c => ({ key: c.payload.key, ...c.payload.val() })); 
 
    }); 
 

 

 
    } 
 

 
}

portafolio.component.html

<div class="container mt-5"> 
<h1>Portafolio</h1> 
<div class="row"> 
    <div class="col-md-4" *ngFor="let proyecto of proyectos | async"> 
     <div class="card my-3"> 
      <div class="card-body"> 
       <h4 class="card-title">{{ proyecto.titulo }}</h4> 
       <a class="btn btn-primary" [routerLink]="['/portafolio', proyecto.key]">Ver detalles</a> 
      </div> 
     </div> 
    </div> 
</div> 

0
votes
answers
6 views
+10

typescipt:爲cryptocompare coinlist API

1

我試圖做一個打字稿接口,爲cryptocompare coinlist API創建界面(https://www.cryptocompare.com/api/data/coinlist/typescipt:爲cryptocompare coinlist API

我已經嘗試過目前這樣的:

interface CoinListResponse { 
    Response: string, 
    Message: string, 
    BaseImageUrl: string, 
    BaseLinkUrl: string, 
    Type: number, 
    Data: Array<Coin> 
} 

現在,這部分作品但Data: Array<Coin>存在問題,因爲Data不是數組而是對象。你可以在這裏看到documenation:https://www.cryptocompare.com/api/#-api-data-coinlist-

這是我想解決什麼: example code

這是硬幣接口:

export interface Coin { 
    Id: number, 
    Url: string, 
    Name: string, 
    CoinName: string, 
    FullName: string, 
    Algorithm: string, 
    ProofType: string, 
    SortOrder: number 
} 

這可能嗎?

非常感謝。

+0

但..數據是否有你正在返回'可觀察'因爲你是有原因的不處理數組? –

+0

@SurajRao我想用作數組 – DazDylz

沙发
0
0

根據API JSON響應定義:

"Data": { 
     "LTC": { 
      "Id": "3808", 
      "Url": "/coins/ltc/overview", 
      "ImageUrl": "/media/19782/ltc.png", 
      "Name": "LTC", 
      "CoinName": "Litecoin", 
      "FullName": "Litecoin (LTC)", 
      "Algorithm": "Scrypt", 
      "ProofType": "PoW", 
      "SortOrder": "2" 
     } 
     ... 
    }, 

Data屬性可以被建模爲一個鍵 - 值對類型,其中關鍵是貨幣名稱(string),值是??類型的。

export interface CoinData { 
    [key: string]: Coin 
}; 

interface CoinListResponse { 
    Response: string, 
    Message: string, 
    BaseImageUrl: string, 
    BaseLinkUrl: string, 
    Type: number, 
    Data: CoinData 
} 
+0

嗯。這是更近一步,但現在我得到'[ts]運算符'<='不能應用於類型'硬幣'和'數字'。' – DazDylz

+0

這是因爲你必須通過名稱訪問特定的貨幣:'coin ['LTC' ] .SortOrder'。否則,你正在訪問整個哈希集,其中包含多種貨幣及其數據。 –

+0

謝謝。我希望它是可迭代的。請參閱下面的我的回答。 – DazDylz

板凳
0
0

解決方案不必須中將sortOrder either.I認爲這將是內部data.And另一個對象[ts] Operator '<=' cannot be applied to types 'Coin' and 'number'.

export function coins$(): Observable<any> { 
    const response = WebRequest.json<CoinListResponse>(`${API_BASE}/data/all/coinlist`); 
    return Observable.fromPromise(response) 
     .map(response => response.Data) 
     .map(coins => Object.values(coins).filter(coin => coin.SortOrder <= COIN_LIMIT)); 
}; 
0
votes
answers
6 views
+10

Ionic | TypeError | fs.createWriteStream不是函數

1

我想創建一個示例excel文件,但我得到錯誤'fs.createWriteStream不是一個函數'。下面 是代碼來創建文件 -Ionic | TypeError | fs.createWriteStream不是函數

import { Component } from '@angular/core'; 
import { NavController, Platform } from 'ionic-angular'; 
import * as Excel from "exceljs/dist/exceljs.js"; 

@Component({ 
    selector: 'page-home', 
    templateUrl: 'home.html' 
}) 
export class HomePage { 

    constructor(platform: Platform) { 
    platform.ready().then(() => { 
     this.createSheetUsingExcelJs(); 
    }); 
    } 

    ionViewDidLoad() { 
    } 

    createSheetUsingExcelJs() { 
    let workbook = new Excel.Workbook(); 
    var worksheet = workbook.addWorksheet('My Sheet'); 

    worksheet.columns = [ 
     { header: 'Id', key: 'id', width: 10 }, 
     { header: 'Name', key: 'name', width: 32 }, 
     { header: 'D.O.B.', key: 'DOB', width: 10 } 
    ]; 
    worksheet.addRow({ id: 1, name: 'Ionic Android', dob: new Date(1970, 1, 1) }); 
    worksheet.addRow({ id: 2, name: 'Ionic iOS', dob: new Date(1965, 1, 7) }); 
    var tempFilePath = 'C:/Users/mahmad/Downloads/temp.xlsx'; 
    console.log(workbook); 

    workbook.xlsx.writeFile('temp.xlsx').then(function() { 
     console.log('file is written'); 
    }); 
    } 
} 

請提出一個解決方案來解決這個問題

沙发
0
0

import * as Excel from "exceljs/dist/exceljs.js";

從JavaScript文件導入打字稿,您需要使用圖書館的類型定義文件。

它在npm可用。

務必:

npm i @types/exceljs --save-dev 

爲了導入:

import * as Excel from 'exceljs'; 

您可以在 「DefinitelyTyped」 測試文件repo

+0

我試着用命令,但現在我得到錯誤「遺漏的類型錯誤:無法讀取屬性未定義的‘原型’」。 – user320676

+0

任何想法它扔在哪裏?也許值得提出一個github問題請求,如果問題與lib –

+0

它被拋出啓動屏幕上。即使我的主頁構造函數沒有調用。 – user320676

板凳
0
0

最後,任務是通過使用ts-xlsx library做檢查樣本。 下面是我的代碼 -

import { Component, Injectable } from '@angular/core'; 
import { NavController, Platform } from 'ionic-angular'; 
import * as XLSX from 'ts-xlsx'; 
import { File } from '@ionic-native/file'; 
import { EmailComposer } from '@ionic-native/email-composer'; 

declare var cordova: any; 
declare var window; 

@Component({ 
    selector: 'page-home', 
    templateUrl: 'home.html', 
    providers: [File] 
}) 

@Injectable() 
export class HomePage { 

    sheetNames: string[] = [] 
    sheets: any; 

    constructor(public emailComposer: EmailComposer, platform: Platform, public file: File) { 
    var objects = [["Header 1", "Header 2", "Header 3"], ["Value 1 1", "Value 1 2", "Value 1 3"], ["Value 2 1", "Value 2 2", "Value 2 3"]]; 

    platform.ready().then(() => { 
     console.log(cordova.file.externalCacheDirectory + "report.xlsx"); 
     this.createXSLX(objects); 
     this.sendEmail(cordova.file.externalCacheDirectory + "report.xlsx"); 
    }); 
    } 

    createXSLX(data: any) { 

    var pathFile = ""; 
    var fileName = "report.xlsx"; 
    let ws_name = "OrderDetails"; 

    let wb: XLSX.IWorkBook = { 
     SheetNames: [], 
     Sheets: {}, 
     Props: {} 

    }; 
    let ws = this.sheet_from_array_of_arrays(data, {}); 

    /* add worksheet to workbook */ 
    wb.SheetNames.push(ws_name); 
    wb.Sheets[ws_name] = ws; 
    let wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' }); 

    let xslxBlob = new Blob([this.s2ab(wbout)], { type: "application/octet-stream" }); 
    pathFile = cordova.file.externalCacheDirectory; 
    this.file.writeFile(pathFile, fileName, xslxBlob); 
    }  

    sendEmail(data) {  
    this.emailComposer.isAvailable().then((available: boolean) => { 
     if (available) { 
     //Now we know we can send 
     } 
    }); 

    let email = { 
     to: '', 
     attachments: [data], 
     subject: 'XLSX File', 
     body: 'How are you? Nice greetings from Leipzig', 
     isHtml: true 
    }; 

    // Send a text message using default options 
    this.emailComposer.open(email); 
    } 


    datenum(v, date1904): any { 
    if (date1904) v += 1462; 
    let epoch: any = Date.parse(v); 
    return (epoch - new Date(Date.UTC(1899, 11, 30)).getTime())/(24 * 60 * 60 * 1000); 
    } 

    sheet_from_array_of_arrays(data, opts) { 
    let ws = {}; 
    let range = { s: { c: 10000000, r: 10000000 }, e: { c: 0, r: 0 } }; 
    for (let R = 0; R != data.length; ++R) { 
     for (let C = 0; C != data[R].length; ++C) { 
     if (range.s.r > R) range.s.r = R; 
     if (range.s.c > C) range.s.c = C; 
     if (range.e.r < R) range.e.r = R; 
     if (range.e.c < C) range.e.c = C; 
     let cell: any = { v: data[R][C] }; 
     if (cell.v == null) continue; 
     let cell_ref = XLSX.utils.encode_cell({ c: C, r: R }); 

     if (typeof cell.v === 'number') cell.t = 'n'; 
     else if (typeof cell.v === 'boolean') cell.t = 'b'; 
     else if (cell.v instanceof Date) { 
      cell.t = 'n'; 
      //cell.z = XLSX.SSF._table[14]; 
      cell.v = this.datenum(cell.v, null); 
     } 
     else cell.t = 's'; 

     ws[cell_ref] = cell; 
     } 
    } 
    if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range.s, range.e); 
    return ws; 
    } 

    s2ab(s) { 
    let buf = new ArrayBuffer(s.length); 
    let view = new Uint8Array(buf); 
    for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF; 
    return buf; 
    } 
} 
0
votes
answers
6 views
+10

.tsx沒有轉換爲.jsx

0

我的.tsx文件沒有轉換爲.jsx和.js.tsx沒有轉換爲.jsx

我正在使用visual studio代碼。保存.tsx文件不會轉換爲.jsx文件。我需要爲此安裝任何插件嗎?

下面是我tsconfig.json

{ 
 
    "compileOnSave": true, 
 
    "compilerOptions": { 
 
    "outDir": "build/dist", 
 
    "module": "esnext", 
 
    "target": "es5", 
 
    "lib": ["es6", "dom"], 
 
    "sourceMap": true, 
 
    "allowJs": true, 
 
    "jsx": "react", 
 
    "moduleResolution": "node", 
 
    "rootDir": "src", 
 
    "forceConsistentCasingInFileNames": true, 
 
    "noImplicitReturns": true, 
 
    "noImplicitThis": true, 
 
    "noImplicitAny": true, 
 
    "strictNullChecks": true, 
 
    "suppressImplicitAnyIndexErrors": true, 
 
    "noUnusedLocals": true 
 
    }, 
 
    "exclude": [ 
 
    "node_modules", 
 
    "build", 
 
    "scripts", 
 
    "acceptance-tests", 
 
    "webpack", 
 
    "jest", 
 
    "src/setupTests.ts" 
 
    ] 
 
}

沙发
0
0

如果你的文件越來越轉化爲.js,你想.jsx相反,這是因爲打字稿是TS代碼轉換爲實際的JS代碼,根據需要注入React節點。那是因爲

"jsx": "react" 

您對您的文件擁有的財產。

如果你想保留作出反應的語法和有它輸出擴展爲.jsx,做

"jsx": "preserve" 

正如所解釋的in the handbook

+0

不,它沒有被轉換成.js太:( –

0
votes
answers
6 views
+10

將存儲的包含html標籤的字符串轉換爲html文本格式

1

我有一個存儲Firebase數據的Angular項目。數據以字符串形式存儲在數據庫中(prdName: string;)。我想問一下,如果我在像<b>this is text</b>這樣的字符串中加入了一個html標記並將其存儲,然後將它們綁定/查看爲html文本格式,是否有可能? (文字成爲粗體)將存儲的包含html標籤的字符串轉換爲html文本格式

firebase

//service.ts 
 
getData() { 
 
    this.List = this.firebase.list('Product'); 
 
    return this.List; 
 
} 
 

 
insertProduct(Product: Product) { 
 
    this.productList.push({ 
 
    prdName: Product.prdName, 
 
    prdCategory: Product.prdCategory, 
 
    prdSup: Product.prdSup, 
 
    prdImage: Product.prdImage, 
 
    prdDescription: Product.prdDescription 
 
    }); 
 
}

//component.ts 
 
ngOnInit() { 
 
    var x = this.ListService.getData(); 
 
    x.snapshotChanges().subscribe(item => { 
 
    this.List = []; 
 
    item.forEach(element => { 
 
     var y = element.payload.toJSON(); 
 
     y["$prdKey"] = element.key; 
 
     this.List.push(y as List); 
 
    }); 
 
    }); 
 
}
<!--component.html--> 
 
<label>Product Name: </label> {{ListService.selectedProduct.prdName}}

請讓我知道,如果需要更多的片段。非常感謝你提前。

沙发
0
1

你必須使用innerHTML綁定HTML標籤:

<div [innerHTML]="ListService.selectedProduct.prdName"></div> 

檢查:https://angular.io/guide/template-syntax#!#property-binding-or-interpolation-

板凳
0
1

我在我的項目,使使用這種管道將其工作的權利

import { PipeTransform, Pipe } from '@angular/core'; 
import { DomSanitizer } from '@angular/platform-browser' 

@Pipe({ name: 'safeHtml'}) 
export class SafeHtmlPipe implements PipeTransform { 
    constructor(private sanitized: DomSanitizer) {} 

    transform(value) { 
    return this.sanitized.bypassSecurityTrustHtml(value); 
    } 
} 

然後在你想要你的html的地方你只需做

<div [innerHTML]="someHtmlContent | safeHtml"></div> 
需要

管,使信任這個網站的內容,更多有關這一點:

https://angular.io/guide/security#bypass-security-apis