2017-02-14 70 views
-2

在JavaScript中,我们可以根据我们通过的剩余参数的数量调用函数作为undefined而不会产生任何错误,它将起作用。以下代码片段供参考在TypeScript提供的参数不匹配调用目标的任何签名“

function test(a,b){ 
 
    if(b){console.log(b)} 
 
    else{console.log('b is undefined')} 
 
    console.log(a) 
 
} 
 
test(5); 
 
test(5,6);

在angular2我服务,称为DataWrapperService

export class DataWrapperService { 
 

 
    constructor(private http: Http) { } 
 
    
 
    getData (URL,interval): Observable<any> { 
 
    if(interval){ 
 
     return Observable 
 
     .interval(interval) 
 
     .flatMap(() => return this.http.get(URL) 
 
       .map(this.extractData) 
 
    }else{ 
 
    return this.http.get(URL) 
 
       .map(this.extractData) 
 
    } 
 
    } 
 
    private extractData (res: Response) { 
 
    let body = res.json(); 
 
    return body || { }; 
 
    } 
 

 
}

而且我用我的测试组件的datawrapper服务。

export class TestComponent implements OnInit { 
 

 
    constructor(private dataWrapper : DataWrapperService) { } 
 

 
    ngOnInit() { 
 
    \t this.getTestData(); 
 
    } 
 

 
    getTestData() { 
 
    \t this.dataWrapper.getData("http://localhost/test").subscribe(data => this.handleTestData(data) 
 
    } 
 

 
    handleTestData(data) { 
 
    \t console.log(data) 
 
    } 
 

 
}

当我试图打电话getData只传递一个参数作为URL打字稿引发错误提供的参数不匹配,调用对象的的任何签名。

+1

刚读出的[手册](https://www.typescriptlang.org/docs/handbook/functions.html#optional-and-default-parameters)。 – 2017-02-14 05:04:45

+0

如果您能接受我的回答,我将不胜感激(不仅因为它是唯一的答案,还因为它可以回答您的问题) – Gab

回答

0

要使函数参数可选,请添加'?'到函数签名中的参数。 例如:

func(param1:string, param2?:string) {} 
+2

为什么选择降价?两个答案都可以解决问题 – Gab

相关问题