我有2个服务文件,我正试图从另一个文件的for循环中的1个服务文件访问方法,但我得到Cannot read property of undefined error
。在以下实现中,我只想将第一个服务文件中的值返回到包含publish
方法的第二个服务文件中。如何解决此问题?
这是我的第一个service.ts文件
@Injectable()
export class MessageService {
constructor(
private readonly messagePublishService: MessagePublishService,
) {}
message = new ProductMessage();
publishMessages(productEvent: ProductEvent): Observable<any> {
var source: string;
let sourceArn = this.configService.get(source);
const url = this.configService.get('SITEMAP_ENDPOINT');
const urls = [url + '/sitemap/retrieve/ide', url + '/sitemap/retrieve/tpd'];
try {
for (let i = 0; i < urls.length; i++) {
return https.get(urls[i], res => {
res.on('data', function(chunk) {
json += chunk;
});
res.on('end', function() {
const result = JSON.parse(json);
getProductCodes(productEvent, result, this.messagePublishService);
});
});
}
} catch (err) {
console.error(err);
}
}
}
function getProductCodes(
productEvent,
result,
messagePublishService: MessagePublishService,
) {
const splitCodes = productEvent.productCodes.split(',');
for (let i = 0; i < result.length; i++) {
for (let j = 0; j < result[i].products.length; j++) {
if (
productEvent.productCodes.length !== 0 &&
productEvent.productCodes !== undefined
) {
for (let k = 0; k < splitCodes.length; k++) {
if (result[i].products[j].productCode === splitCodes[k]) {
messagePublishService.publish( -----------------> TypeError: Cannot read property 'publish' of undefined
this.sourceArn,
result[i].products[j].productCode,
);
}
}
}
}
}
}
这是第二个服务文件,其中包含我要在第一个服务文件中访问的publish method
@Injectable()
export class MessagePublishService {
constructor(private readonly configService: ConfigService) {}
async publish(source: string, message: ProductMessage) {
let messageString = JSON.stringify(message);
console.log(
'MessagePublishService.publish - entry: %s, %s',
source,
messageString,
);
let sourceArn = this.configService.get(source);
// Create publish parameters
var params = {
Message: messageString /* required */,
TopicArn: sourceArn,
};
let messageId: string = 'NULL';
console.log('MessagePublishService.publish - exit');
}
}