gpt4 book ai didi

javascript - Typescript 认为响应数组是一个对象

转载 作者:搜寻专家 更新时间:2023-10-30 21:49:36 25 4
gpt4 key购买 nike

我有一个 Observable 流,它显然将一个数组输出到订阅 block 中。我正在尝试将响应分配给数组变量以呈现自动完成结果。除了 typescript 错误外,一切正常。

自动完成组件:

@Component({
selector: 'auto-complete',
styleUrls: ['auto-complete.component.scss'],
template: `
<div class="ac-container">
<div class="ac-input">
<input type="text" [(ngModel)]="query" (keyup)="filter()">
</div>
<div class="ac-results" *ngIf="results.length > 0">
<ul *ngFor="let item of results">
<li>
<a (click)="select(item)">{{item}}</a>
</li>
</ul>
</div>
</div>
`
})

export class AutoCompleteComponent {
@Input() fn: Function;

public query = '';
public results = [];

filter() {
let value = Observable
.from(this.query)
.throttleTime(20)
.map(value => value)
.distinctUntilChanged()
.map(search => this.fn(search))
.switch()
.subscribe(response => {
this.results = response;
}, error => {}
);
}
}

父组件:

@Component({
selector: 'auto-completor',
template: `<auto-complete [fn]="apiSearch"></auto-complete>`
})

export class AppComponent implements OnInit {
public results: any;

constructor(
private service: AppService
) {}

public apiSearch(term) {
return this.service.getSearchData(term);
}

ngOnInit() {
this.apiSearch = this.apiSearch.bind(this);
}
}

错误:

enter image description here

IED 错误指示:

enter image description here

我希望我能展示我尝试过的事情的例子,但我所做的一切都被谷歌搜索到了。我不知道。谢谢。

编辑/添加

假 DB/Http 响应

从'@angular/core'导入{Injectable};

@Injectable()
export class Database {
private FAILURE_COEFF = 10;
private MAX_SERVER_LATENCY = 200;

private getRandomBool(n) {
var maxRandomCoeff = 1000;
if (n > maxRandomCoeff) n = maxRandomCoeff;
return Math.floor(Math.random() * maxRandomCoeff) % n === 0;
}

public getSuggestions(text) {
var pre = 'pre';
var post = 'post';
var results = [];
if (this.getRandomBool(2)) {
results.push(pre + text);
}
if (this.getRandomBool(2)) {
results.push(text);
}
if (this.getRandomBool(2)) {
results.push(text + post);
}
if (this.getRandomBool(2)) {
results.push(pre + text + post);
}

return new Promise((resolve, reject) => {
var randomTimeout = Math.random() * this.MAX_SERVER_LATENCY;
setTimeout(() => {
if (this.getRandomBool(this.FAILURE_COEFF)) {
reject();
} else {
resolve(results);
}
}, randomTimeout);
});
}
}

应用服务将 promise 响应转换为 Observable

export class AppService {

constructor(
private database: Database
) {}

public getSearchData(term) {
return Observable.defer(() => {
return Observable.fromPromise(this.database.getSuggestions(term)
.then(function(res) {
return res;
})
);
})
}
}

最佳答案

问题是 Observable 没有类型化,因为你的函数 fn 没有调用签名。我目前无法检查它,但如果你给 fn 一个 lambda 表达式调用签名,则可观察对象可能会接管它的类型,使你能够将它分配给结果。

@Input() fn: (string) => string[];

或者,您可以按任何类型输入结果,但这只是一种快速且非常肮脏的解决方法,可以完全删除类型。

关于javascript - Typescript 认为响应数组是一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47911845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com